我有两个表AspNetUsers
和AspNetRoles
,表AspNetUserRoles
中存在多对依赖关系。我想显示任何具有他角色的用户(如果role为null我想显示它)。
在SQL查询中是:
SELECT u.Email, u.FirstName, u.LastName, r.Name as 'Role'
FROM AspNetUserRoles as ur
RIGHT JOIN AspNetUsers as u
ON ur.UserId = u.Id
LEFT JOIN AspNetRoles as r
ON ur.RoleId = r.Id
我想将其转换为LINQ查询。我为AspNetUserRoles
表和检索数据编写查询,但只有拥有角色的用户才会显示结果。
IQueryable<RoleViewModel> result = from user in context.AspNetUsers
from r in user.AspNetRoles
select new RoleViewModel{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r.Name
};
你能帮助我吗?
修改
这是工作:
IQueryable<RoleViewModel> result = from user in context.AspNetUsers
from r in user.AspNetRoles.DefaultIfEmpty()
select new RoleViewModel{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r != null ? r.Name : null
};
答案 0 :(得分:0)
使用DefaultIfEmtpy
方法加入linq:
var result = from user in context.UserEntities
from r in user.RoleEntities.DefaultIfEmpty()
select new
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r != null ? r.RoleName : null
};