Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Query for inner join

What would be the query for:

select s.* from Service s  inner join ServiceAssignment sa on sa.ServiceId = s.Id where  sa.LocationId = 1 

in entity framework?

This is what I wrote:

 var serv = (from s in db.Services                 join sl in Location on s.id equals sl.id                 where sl.id = s.id                 select s).ToList(); 

but it's wrong. Can some one guide me to the path?

like image 443
TheWebs Avatar asked Apr 15 '13 21:04

TheWebs


People also ask

How do I use joins in Entity Framework?

Method SyntaxFirst join the first two tables. Employees is the outer table and People is the inner table. Project the properties you want to in the output. Also include those properties, which you want to use in the join condition further down the query.

How use inner join in LINQ query?

A simple inner join that correlates elements from two data sources based on a simple key. An inner join that correlates elements from two data sources based on a composite key. A composite key, which is a key that consists of more than one value, enables you to correlate elements based on more than one property.

Is LINQ join inner or outer?

When you use the LINQ join clause in the query expression syntax to combine two sets of related information, you perform an inner join. This means that you provide an expression that determines for each item in the first sequence, the matching items in the second.


2 Answers

from s in db.Services join sa in db.ServiceAssignments on s.Id equals sa.ServiceId where sa.LocationId == 1 select s 

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]        -- other fields from Services table FROM [dbo].[Services] AS [Extent1] INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]     ON [Extent1].[Id] = [Extent2].[ServiceId] WHERE [Extent2].[LocationId] = 1 
like image 78
Sergey Berezovskiy Avatar answered Oct 02 '22 04:10

Sergey Berezovskiy


In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1); 

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments,       s => s.Id,      sa => sa.ServiceId,       (s, sa) => new {service = s, asgnmt = sa}) .Where(ssa => ssa.asgnmt.LocationId == 1) .Select(ssa => ssa.service); 
like image 27
Michael Blackburn Avatar answered Oct 02 '22 03:10

Michael Blackburn