2017-09-04 70 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();