如何在EF代码中首先建立模型和枚举之间的多对多关系?

时间:2014-08-23 00:36:57

标签: c# entity-framework orm ef-code-first code-first

例如:

public class Role
{
    public Role()
    {
        Permissions = new HashSet<Permission>();
    }

    public string ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Permission> Permissions { get; set; }
}

public enum Permission
{
    UserManagement = 0,
    DepartmentManagement = 1,
    RoleManagement = 2,
    ModifyPassword = 3
}

通常,在模型和另一个模型之间,我可以编写两个导航属性。但是对于这种情况,我无法在枚举中写入导航属性。

1 个答案:

答案 0 :(得分:4)

你可以这样做吗?

[Flags]
public enum Permission
{
    UserManagement = 1,
    DepartmentManagement = 2,
    RoleManagement = 4,
    ModifyPassword = 8
}

public class Role
{
    public string ID { get; set; }
    public string Name { get; set; }
    public Permission Permissions { get; set; }
}

然后,例如:

var role = new Role();
//assign multiple values
role.Permissions = Permission.UserManagement | Permission.ModifyPassword;
//add a value
role.Permissions |= Permission.DepartmentManagement;
//remove a value
role.Permissions &= ~Permission.DepartmentManagement;
//test for a value
bool hasPermission = (role.Permissions & Permission.ModifyPassword) != 0;

警告:

可能考虑暴露一些方法,如RemovePermission(...)AddPermission(...)等,如果有人误操作按位操作,就会更难引入一个非常重要的错误。

除非是性能要求或其他什么,否则我可能只是将权限设为一个类并承担开销。

一些阅读: