Linq to Entities EF4

11

我有一个Groups领域模型,其中包含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.

非常感谢您的帮助!


为什么不删除最后一个Contains子句,将其包装到您的选择语句中呢? - Rig
Rig,你能展示一下查询语句是什么样子吗? - Lavan
2个回答

14

移除对用户对象的空值测试,无论如何它都是惰性加载的,你的用户对象是虚拟的吗?如果是,那么它就是惰性加载的,因此可以删除空值测试。

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

2
可以删除空值测试。我们正在编写的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

0

你不能反过来走吗?

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

希望这能有所帮助。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接