简体   繁体   中英

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....

在此输入图像描述

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM