简体   繁体   中英

Linq to Entities EF4

I have a Groups domain model with name , desc and collection of users (belonging to the group)

I am trying to get all groups that a particular user belongs to. This is my LinQ statement:

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;

I get the following error when i try to execute the query

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

Any help is appreciated.Thanks!

Remove the null testing for Users object, anyway it's lazy loaded, is your Users virtual? if it is, it is lazy-loaded, it's ok to remove the null testing then

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

Can't you go the opposite way?

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM