0

有问题的型号:

public class EmployeeType
{
    public int employeeTypeId { get; set; }
    public string typeName { get; set; }
    public virtual List<Employee> Employees { get; set; }
}

public class Employee
{
    public int employeeId { get; set; }
    public string userName { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string password { get; set; }
    public int employeeTypeId { get; set; }

    public virtual EmployeeType EmployeeTypes { get; set; }
    public virtual List<PhoneNumber> PhoneNumbers { get; set; }
}

目前我正在通过以下方式添加不同的值:

db.EmployeeType.Add(new EmployeeType
{
    typeName = "Administrator"
});
db.EmployeeType.Add(new EmployeeType
{
    typeName = "Seller"
});
db.EmployeeType.Add(new EmployeeType
{
    typeName = "Accountant"
});

但是在我必须检查用户是否是管理员等情况下,我必须检查 linq 查询并确定 id 是否等于 Employee 表中的 id。

我如何在 EmployeeType 模型中定义默认记录,而不是通过多个 .Add 行添加值,这样我就可以使用这样的东西:

if (db.Employee.FirstOrDefault(o => ...).servictypeId 
== EmployeeType.Administrator)
{ 

}
4

1 回答 1

0

处理此问题的最佳方法是将employeetypeId 转换为EF 中的枚举。您可以通过将字段“转换”为 EDMX 中的枚举轻松实现此目的。只需右键单击 edmx 模型设计屏幕中的属性,然后单击“转换为枚举”。

首先,您需要创建一个名为 UserRole 的枚举:-

enum UserRole : int
{
    Administrator = 1,
    Manager = 2,
    Client = 3

}

现在,当您想创建新的 UserRole 时,将它们添加到您的 Enum 中。

在添加新用户时,您只需执行以下操作:-

new User object1 { Name = "Fred", UserRole = UserRole.Client};

dbContext.Save(object1);

EF 会知道在数据库中将employeeTypeId 保存为3。

优势变得更好,因为现在您可以说:-

if(User.UserRole == UserRole.Adminstartor)
{
  //Do Stuff
}
于 2013-10-13T21:01:36.250 回答