C# 内部联接的实体框架查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16025287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:44:56  来源:igfitidea点击:

Entity Framework Query for inner join

c#entity-framework

提问by TheWebs

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?

但这是错误的。有人可以指导我走这条路吗?

采纳答案by Sergey Berezovskiy

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

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

哪里db是你的DbContext。生成的查询将如下所示(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

回答by The Lonely Coder

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

回答by Michael Blackburn

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