Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining many-to-many tables in Entity Framework

I have a table layout as shown in this image. One main table (User), and two many-to-many tables (Preference and Location) with junction tables. I have set up the correct relationships in the data model to allow selections from these m-2-m tables....

enter image description here

The report tool I'm writing allows the user to select (from a checklist) any user preferences or user locations. What I'd like to do is choose only the records from the User table where the Preferences OR Locations contains at least one of their selections.

Is this possible with a Linq query? (I did previously do this in SQL, but it seemed easier to write in Linq until I got to this part!)

Many thanks,

EDIT: Visual Studio 2012, Entity Framework 4, SQL Server 2008 R2

like image 807
Simon Avatar asked Oct 20 '22 21:10

Simon


1 Answers

from u in Users
where u.Locations.Any(l => l.Name == value) ||
      u.Preferences.Any(p => p.Title == value)
select u;

That will generate two EXISTS subqueries. Lambda syntax:

Users.Where(u => u.Locations.Any(l => l.Name == value) ||
                 u.Preferences.Any(p => p.Title == value));
like image 179
Sergey Berezovskiy Avatar answered Oct 23 '22 16:10

Sergey Berezovskiy