0

我的网站上有 3 个实体,它们有很多组合。

我将创建以下层次结构:

  1. 每个用户都有一组用户角色。
  2. 每个 UserRole 都有固定的 PermissionRecords 集合
  3. 每个 PermissionRecord 都有一个 PermissionRecordPrivileges 字段,该字段因用户而异。

我想获得用户的权限(获得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; }

}
4

2 回答 2

1

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

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是一个包含 aUser的 id 的变量。

于 2012-12-03T15:10:24.700 回答
0

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

注意:当您使用实体框架代码优先时,需要维护约定(命名和单数/复数)。如下所示

实体模型

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

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

于 2012-12-02T13:56:41.550 回答