Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 353
Lavan Avatar asked Aug 15 '11 16:08

Lavan


People also ask

Which is correct about LINQ to entities?

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity Framework are represented by command tree queries, which execute against the object context.

Can I use LINQ with Entity Framework?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries. It uses your derived context and entity classes to reference database objects.

What is the difference between Entity Framework and LINQ?

Entity Framework is an object-relational mapping (ORM) framework for connecting C# code to external databases, usually SQL Server. LINQ is a query language embedded into C# and a set of extension methods in order to make it useful.

Can we use LINQ without Entity Framework?

No. Linq as in query over the data-in-memory that was loaded using your stored procedures (which means that your queries won't be translated to SQL)?


1 Answers

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;
like image 103
Michael Buen Avatar answered Oct 05 '22 10:10

Michael Buen