问题 Linq to Entities EF4


我有一个群组域模型 namedesc 和收集 users(属于该组)

我正在尝试获取特定用户所属的所有组。这是我的LinQ声明:

var results = from p in AuthorizationService.UnitOfWork.Groups.FindAll()
                          where
                              (p.Users != null && p.Users.Select(u => u.Id).Contains(CurrentUser.Id))
                          select p.Name;

我尝试执行查询时收到以下错误

Cannot compare elements of type 'System.Collections.Generic.ICollection`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supported.

任何帮助表示赞赏。谢谢!


9023
2017-08-15 16:09


起源

为什么不删除最后一个Contains子句并将其包装到您的选择中? - Rig
你能告诉我查询的样子吗? - Lavan


答案:


删除Users对象的null测试,无论如何它是延迟加载的,你的用户是虚拟的吗?如果是,它是延迟加载的,那么可以删除null测试

var results = 
from p in AuthorizationService.UnitOfWork.Groups.FindAll() 
where 
     p.Users.Any(u => u.Id == CurrentUser.Id)
select p.Name;

14
2017-08-15 16:22



迈克尔,它抛出同样的错误 - Lavan
迈克尔,删除空测试实际上工作。 - Lavan
你试过删除吗? p.Users != null? - Michael Buen
可以删除null测试。 Linq to Entities(不是Linq to objects)我们正在编写的只是被翻译成字符串。 EF在对象比较方面并不那么聪明。例如,这个Linq在NHibernate中被允许: from p in person where p != null,它会自动翻译 select * from person where p.Id is not null虽然EF Linq要求你把它们比作原始类型,所以你必须写 from p in person where p.Id != null - Michael Buen


你不能走相反的方向吗?

var results = AuthorizationService.UnitOfWork.Users.Include("Groups").First(u => u.ID == CurrentUser.Id).Select(u => u.Groups);

希望这可以帮助。


0
2017-08-15 16:20



谢谢anton,但我不允许更改现有模型。 - Lavan