2017-09-04 71 views
1

我想比较两个不同表中的两个列表UserGroup使用单个查询,即通过不多次访问数据库。比较匹配元素在Iqueryable中使用单个查询

当前我在一个查询中提取所有分配的UserGroup,并与其他查询中允许的所有Usergroup进行比较。

var query = _context.AppSubOperationUserGroupMappings.Where(filterPredicate) 
                  .Select(x => x.UserGroup) 
                  .ToList(); 

    var allowedUserGroups = _context.Users.Where(x => x.Id == userId) 
               .Select(x => x.UserGroupUserMappings.Select(y => y.UserGroup)) 
               .First() 
               .ToList(); 

    return query.Any(a => allowedUserGroups.Any(b => b.Id == a.Id)); 

如何将它们合并到单个查询中?

+0

您是否尝试过简单地丢弃'.ToList'在查询中。这应该导致一个数据库查询。 – Sefe

回答

0

删除ToList首先,使用加入的SelectMany

var query = _context.AppSubOperationUserGroupMappings.Where(filterPredicate) 
    .Select(x => x.UserGroup); 

var allowedUserGroups = _context.Users.Where(x => x.Id == userId) 
    .SelectMany(x => x.UserGroupUserMappings, (x, y) => y.UserGroup); 

return query 
    .Join(
     allowedUserGroups, 
     x => x.Id, 
     x => x.Id, 
     (x, y) => false) // doesn't matter what to select 
    .Any();