内部联接的实体框架查询

The*_*ebs 60 c# entity-framework

什么是查询:

select s.* from Service s 
inner join ServiceAssignment sa on sa.ServiceId = s.Id
where  sa.LocationId = 1
Run Code Online (Sandbox Code Playgroud)

在实体框架中?

这就是我写的:

 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();
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*kiy 91

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • @JoSmo如果你有一个导航属性(从下面的例子)你可以使用方法语法没问题.但如果没有,它看起来像这样(非常毛茸茸):`db.Services.Join(db.ServiceAssignments,s => s.Id,sa => sa.ServiceId,(s,sa)=> new {service = s,alert = sa}).其中(ssa => ssa.alert.LocationId == 1).Select(ssa => ssa.service);` (4认同)
  • @JonathanWood不,那是内连接.左外连接将由组连接生成. (3认同)
  • 这不是左外连接吗? (2认同)

Mic*_*urn 49

如果有人对Method语法感兴趣,如果你有一个导航属性,那很容易:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
Run Code Online (Sandbox Code Playgroud)

如果你不这样做,除非有一些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);
Run Code Online (Sandbox Code Playgroud)

  • @Cardin在那种情况下我会建议C#6?运营商.如果您没有,请在使用navigation属性之前检查null.通常,您不会在示例中添加一堆防御性代码,以免混淆主要观点.如果FK可以为空,它将如下所示:(C#6)`db.Services.Where(s => s?.ServiceAssignment.LocationId == 1);`或者在C#5中这样:`db. Services.Where(s => s.ServiceAssignment!= null && s.ServiceAssignment.LocationId == 1);` (3认同)

The*_*der 6

如果可用,您可以使用导航属性.它在SQL中生成内部联接.

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s
Run Code Online (Sandbox Code Playgroud)