Linq to Entities EF4

时间:2011-08-15 16:09:26

标签: c# linq entity-framework

我的群组域模型包含namedescusers的集合(属于该群组)

我正在尝试获取特定用户所属的所有群组。这是我的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.

感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分:0)

你能不能采取相反的方式吗?

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

希望这有帮助。