获取资源 - 活动对列表。实体框架

时间:2015-01-22 15:10:45

标签: c# sql .net entity-framework many-to-many

  1. 以下是我在项目中使用的 DbContext 模型的要点 - DbContextModels
  2. 以下是这些关系:
    • User - Role M M
    • Role - Activity - Resource M 中号中号
  3. 联接表明确定义为 RoleResourceActivity
  4. 考虑种子方法 - DbContextSeed
  5. 以下是我使用Linq尝试实现的基本 sql - 查询:

    select
        r.Name [resource], a.Name
    from Activities a
        join RoleResourceActivities ra on ra.ActivityId = a.Id
        join Resources r on ra.ResourceId = r.Id
        join Roles ro on ra.RoleId = ro.Id
        join UserRoles ur on ur.Role_Id = ro.Id
        join Users u on ur.User_Id = u.Id
    where u.Username = 'User'
    group by r.Name, a.Name
    

    用户 User2 的结果相应:

    enter image description here

    问题

    如何编写这样的linq-query,以便结果集包含投影对象,如:

    new {
        Resource = Resource.Name,
        Activities = ListOfCorrespondingActivities
    }
    

    JSON

    // Username: `User`, Roles: "SimpleUser", "AdvancedUser"
    [
         {Resource: "blogs", Activities: ["Delete", "Read", "Update"]},
         {Resource: "talks", Activities: ["Delete", "Read", "Update"]}
    ]
    
    // Username: `User2`, Roles: "SimpleUser"
    [
         {Resource: "blogs", Activities: ["Read"]},
         {Resource: "talks", Activities: ["Read"]}
    ]
    

1 个答案:

答案 0 :(得分:1)

您可以使用此方法从用户中找到资源和相关活动:

public ILookup<string,string> GetResourcesAndActivitiesByUser(string userName)
{
        using (var _db = new AppDbContext())
        {
            return (from u in _db.Users
                    where u.UserName == userName
                    from a in _db.Activities
                    join ra in _db.RoleResourceActivities on a.Id equals ra.ActivityId
                    join r in _db.Resources on ra.ResourceId equals r.Id
                    join ro in _db.Roles on ra.RoleId equals ro.Id
                    where u.Roles.Contains(ro)
                    select new { Resource = r.Name, Activity = a.Name })
                    .ToLookup(e => e.Resource, e => e.Activity);
        }
}

如果您要在问题中显示的匿名类型中创建IEnumerable<>,则可以执行以下操作:

 var resources = GetResourcesAndActivitiesByUser("UserX").Select(e=>new {Resource=e.Key,Activities=e.ToList()});