Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to Many select in LINQ to Entities

I have two tables Service and Provider. Between them is a joining table ServiceProvider which has only 2 fields - one for each of the two PKs. When added to the edmx the joining many-to-many table is abstracted away and can't be seen (as expected).

This is all fine except when I want to get Providers based on a given service. From this question:

it looks like the answer would be simply:

var query = from p in entities.Providers
            from s in entities.Services
            where s.Id == 15
            select p;

but this returns ALL providers. What am I doing wrong here?

like image 727
finoutlook Avatar asked Jun 21 '12 11:06

finoutlook


3 Answers

var query = entities.Providers.FirstOrDefault(p => p.Id == 15).Services.ToList();
like image 118
halit Avatar answered Oct 05 '22 06:10

halit


Isn't it as simple as

var matchingProviders = entities.Services.Single(s=>s.Id==15).Providers;
like image 22
Rawling Avatar answered Oct 05 '22 07:10

Rawling


Try this:

var res = from s in entities.Services
          where s.Id == 15
          select s.Provider;

EDIT

Corrected and tested the query on real-life model and data. It works now.

like image 43
Maciej Avatar answered Oct 05 '22 07:10

Maciej