外键表映射

时间:2012-12-02 11:57:38

标签: entity-framework ef-code-first

我有3个实体在我的网站上有很多组合。

我想创建以下层次结构:

  1. 每个用户都有UserRoles的集合。
  2. 每个UserRole都有一个固定的PermissionRecords集合
  3. 每个PermissionRecord都有一个PermissionRecordPrivileges的fild,因用户而异。
  4. 我想获得用户的权限(获取permissionRecord和UserRole集合非常简单)。 据我了解,我需要创建一个合并以下数据的表: UserId,PermissionRecordId,PermissionPrivilegesId(3个创建主键的外键)

    如何使用EF 5(或更早版本)执行此操作?

    代码:

    public class BaseEntity
    {
        public int Id { get; set; }
    }
    public class User:BaseEntity
    {
       public virtual ICollection<UserRole> UserRoles{get;set;}
    }
    
    public class UserRole:BaseEntity
    {
       public ICollection<PermissionRecord> PermissionRecords { get; set; }
    }
    
    public class PermissionRecord : BaseEntity
    {
        public PermissionRecordPrivileges Privileges { get; set; }
    }
    
    public class PermissionRecordPrivileges : BaseEntity
    {
        public bool Create { get; set; }
    
        public bool Read { get; set; }
    
        public bool Update { get; set; }
    
        public bool Delete { get; set; }
    
    }
    

2 个答案:

答案 0 :(得分:1)

您的术语“创建表格”有点令人困惑。表是数据库对象。我假设你的意思是客户端的数据结构。要收集User的权限,您可以执行以下操作:

var privileges = (from u in context.Users
                 from ur in u.UserRoles
                 from pr in ur.PermissionRecords
                 where u.UserId = id
                 select ur.Privileges).Distinct();

其中id是包含User ID的变量。

答案 1 :(得分:0)

您必须创建实体模型类,如下所示。

注意: 当您使用实体框架Code First 约定(命名和单数/复数) >。如下

实体模型

public class UserRole
 {

     public int Id { get; set; }

     public virtual ICollection<PermissionRecord> PermissionRecords { get; set; }

 }


public class PermissionRecord 
 {
    public int Id { get; set; }

    public virtual PermissionRecordPrivilege PermissionRecordPrivilege { get; set; }
 }


public class PermissionRecordPrivilege
 {

    public int Id { get; set; }

    public bool Create { get; set; }

    public bool Read { get; set; }

    public bool Update { get; set; }

    public bool Delete { get; set; }

 }

您的表格应该在

下面

<强>表格

PermissionRecordPrivileges

Id            int    NotNull
Create        bit   AllowNull
Read          bit   AllowNull
Update        bit   AllowNull
Delete        bit   AllowNull


PermissionRecords

Id                             int    NotNull

PermissionRecordPrivilege_Id   int    NotNull

UserRole_Id                    int    NotNull


UserRoles

Id            int    NotNull

我希望这会对你有所帮助。祝你好运。