获取资源-活动对列表。 Entity Framework

Getting a list of Resource-Activities pairs. Entity Framework

  1. 这是我项目中的 DbContextmodels 的要点 - DbContextModels
  2. 这些是关系:
    • User-Role 作为M:M
    • Role-Activity-Resource 作为 M:M:M
  3. Join table 明确定义为 RoleResourceActivity
  4. 考虑 Seed 方法 - DbContextSeed

下面是基本的 sql 我试图通过使用 Linq-query:

实现的目标
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

UserUser2的结果对应:

问题

如何编写这样的 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"]}
]

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

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()});