User
- Role
M : M Role
- Activity
- Resource
M :中号:中号 RoleResourceActivity
以下是我使用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 的结果相应:
问题
如何编写这样的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"]}
]
答案 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()});