Linq any - How to choose

I have a few simple classes that look like this:

Class Favorites Guid UserId Guid ObjectId Class Objects Guid Id String Name 

In the Entity Framework, I want to select all objects that the user has marked as favorites.

So, I tried something like this

 context.Objects.Where( x => x.Id == context.Favorite.Where(f => f.UserId == UserId) .Select(f => f.ObjectId).Any() ); 

But I do not understand. I also tried with intersection, but I understand that this is the most similar type. One user can have many favorites.

+4
source share
5 answers

you can use join clause:

 context.Favorite .Where(f => f.UserId == UserId) .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t); 
+6
source

I would join, my linq would look like this:

 var matches = from o in context.Objects join f in context.Favorite on o.Id equals f.ObjectId where f.UserId == UserId select o; 
+4
source
 from o in context.Objects join f in context.Favorites on o.Id equals f.ObjectId where f.UserId == @userId select //whatever you wants 
+1
source

Use FirstOrDefault () instead of Any ()

0
source

your favorites class requires a property that binds it to objects, and instead of double clauses you can use Include

Classes

 Class Favorites Guid UserId Guid ObjectId [ForeignKey("Id")] Objects objs Class Objects Guid Id String Name 

Linq

 context.Favorites.Include(objs).Where(x => x.UserID == UserID) 

Then the Favorites object will have a collection of objects.

0
source

All Articles