如何使用linq查询从左外部联接表获取子列表?

时间:2020-06-25 18:18:57

标签: c# linq ef-core-3.1

我有用户,角色和一个UserRoles表。我正在尝试获取用户列表,并列出他们所属的所有角色的子列表。

我有以下查询,当我尝试填充子列表时出现问题。尝试使用Object reference not set to an instance of an object IEnumerable时出现rolesGroup错误。我尝试进行空检查,但这会引发另一个错误,提示Null TypeMapping in Sql Tree

知道我应该如何填充Roles子列表吗? 谢谢!

                var q = from u in _dbContext.Users
                        join ur in _dbContext.UserRoles on u.Id equals ur.UserId
                        join r in _dbContext.Roles on ur.RoleId equals r.Id  into rolesGroup
                        from rg in rolesGroup.DefaultIfEmpty()
                        select new UserJS
                        {
                            Id = u.Id,
                            FirstName = u.FirstName,
                            LastName = u.LastName,
                            Roles = rolesGroup.Select(x => x .Name).ToList(), //<--- FAILING HERE
                        };
//DTO
    public class UserJS
    {
        public string Id { get; set; }
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<string> Roles { get; set; }
    }

2 个答案:

答案 0 :(得分:0)

这样写查询:

var q = from u in _dbContext.Users
                        join ur in _dbContext.UserRoles on u.Id equals ur.UserId
                        select new UserJS
                        {
                            Id = u.Id,
                            FirstName = u.FirstName,
                            LastName = u.LastName,
                            Roles =  _dbContext.Roles.Where(x=>x.Id == ur.RoleId).ToListAsync(), 
                        };

答案 1 :(得分:0)

我可以使用select内的子查询来使其工作。

                var q = from u in _dbContext.Users.Include(x => x.Doctor)
                        select new UserJS
                        {
                            Id = u.Id,
                            FirstName = u.FirstName,
                            LastName = u.LastName,
                            Roles = (from ur in _dbContext.UserRoles
                                     join r in _dbContext.Roles on ur.RoleId equals r.Id
                                     where ur.UserId == u.Id
                                     orderby r.Name
                                     select r.Name).ToList(),
                        };