Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq any - How to select

I have some simple classes that looks like this:

Class Favorites
Guid UserId
Guid ObjectId

Class Objects
Guid Id
String Name

With Entity Framework I want to select all the Objects which has been marked as a favorite by a user.

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 don't get it. I also tried with intersect, but what I understand it most be the same type. One User can have many Favorite objects

like image 985
Simon Edström Avatar asked Dec 20 '22 12:12

Simon Edström


2 Answers

you could use join clause:

context.Favorite
  .Where(f => f.UserId == UserId)
  .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t);
like image 163
Kamyar Nazeri Avatar answered Dec 23 '22 01:12

Kamyar Nazeri


I'd do a join, my linq would look like:

var matches = from o in context.Objects
join f in context.Favorite on o.Id equals f.ObjectId
where f.UserId == UserId
select o;
like image 20
Matt Roberts Avatar answered Dec 23 '22 02:12

Matt Roberts