简体   繁体   English

内部联接的实体框架查询

[英]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? 有人可以指导我走这条路吗?

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 . db是你的DbContext Generated query will look like (sample for EF6): 生成的查询看起来像(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

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy: 如果有人对Method语法感兴趣,如果你有一个导航属性,那很容易:

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): 如果你不这样做,除非有一些我不知道的Join()覆盖,我认为它看起来很粗糙(我是一个方法语法纯粹主义者):

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

You could use a navigation property if its available. 如果可用,您可以使用导航属性。 It produces an inner join in the SQL. 它在SQL中生成内部联接。

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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