2013-02-07 76 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;