LINQ User - Role problem

dragos2406
dragos2406 used Ask the Experts™
on
Hello,

I recently met a problem using linq on entities. On the db I have the following tables: User, Role, and UserToRole. Based on that model, the entity framework generated 2 entities: User and Role. An user can have multiple roles, and a role can gather multiple users.

The problem appears when trying to count the users with the role of student, for example (in other words how many students are in my db?).


The error I receive is:
LINQ to Entities does not recognize the method 'Boolean Contains[Role](System.Collections.Generic.IEnumerable`1[Role], Role, System.Collections.Generic.IEqualityComparer`1[Role])' method, and this method cannot be translated into a store expression.

Thank you!
Role student = context.Role.FirstOrDefault( r => r.Name == "Student" );
int students = context.User.Where( u => u.Roles.Contains( student ) ).Count();

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Architect
Commented:
Try the following LINQ query.

int x = (from u in context.User
         where u.Role.Any( r => r.RoleName == "Student" )
         select u).Count();

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial