2013-02-07 78 views
2

我有以下表LINQ請求多到許多

Users 
- ID 
- FirstName 
- LastName 

MultiplyItems 
- ItemID 
- Title 

UserMultiplyItems 
- UserID 
- ItemID 

我有一個可變

List<int> delegateList = {1, 3, 5}; 

其中1,3,5是的ItemID

我想選擇所有用戶,其中至少有一個ItemID鏈接可選用戶。 我嘗試以下操作:

 var result = from i in _dbContext.Users 
        where 
        ((delegateList == null) || i.MultiplyItems.Any(p=> delegateList.Any(a => a == p.ItemID))) 

        select new UserModel() 
        { 
         .... 
        }; 

但它不起作用。錯誤:

Cannot compare elements of type 'System.Collections.Generic.List`1'. Only primitive types, enumeration types and entity types are supported.

如何正確地做到這一點? 感謝

回答

2

我會寫這一個:

var filteredUsers = delegateList == null 
    ? _dbContext.Users 
    : _dbContext.Users.Where(user => user.MultiplyItems 
     .Any(item => delegateList.Contains(item.Id))); 

var result = filteredUsers.Select(user => new UserModel 
     { 
      //the UserModel initialization 
     }); 

你不應該檢查查詢內以下行:

delegateList == null 

它轉換爲SQL和SQL沒有什麼是清單的想法以及如何將它與null進行比較。

0
var result = from i in _dbContext.Users 
    from mi in i.multiplyItems 
    select new yourClass(); 

    if(delegateList!=null) 
    { 
     result = result.Where(delegateList.contains(mi.ItemID)); 
    } 

    result.ToList(); 

我沒有視覺工作室開放測試,但它應該有很多這樣的。

+0

謝謝,但是如何檢查delegateList = null(然後忽略此部分)? –

+0

結構如果不起作用... –

-1

嘗試將其更改爲:

var result = from u in _dbContext.Users 
where 
((delegateList == null) || u.MultiplyItems.Any(mi => delegateList.Contains(mi.ItemID))) 

select new UserModel() 
{ 
.... 
}; 

注意我也改名爲你的「我」和「p」東西「u」和「MI」,使其更易於閱讀。

+0

無法比較'System.Collections.Generic.List'1'類型的元素。只支持原始類型,枚舉類型和實體類型。 –

-1

或者你不能在所有使用LINQ,只是堅持用lambda表達式:

List<UserModel> usersWithItems = 
    context 
    .Users 
    .Where(u => u.MultiplyItems.Any(mi => (delegateList == null) || (delegateList.Contains(mi.ItemID)))) 
    .Select(um => (new UserModel() { ... })) 
    .ToList(); 

其中我個人比較喜歡,這意味着你不需要知道LINQ的。

0

我不確定這是不是你想要的,但我認爲它更好地嘗試和幫助。

這將輸出用戶表中的所有用戶,其中ItemID包含在delegateList中。魔術鋪設在Contains運算符中,您可以從列表中獲得列表a中包含的元素b

var selection = from a in db.UserMultiplyItems 
       from b in db.Users 
       where delegateList.Contains(a.ItemID) && a.UserID == b.ID 
       select b;