使用LINQ实体框架可以获得多对多的检索数据

时间:2015-03-13 02:31:12

标签: sql linq entity-framework

我有两个表AspNetUsersAspNetRoles,表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
                                           };

1 个答案:

答案 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
};