关于c#:内部联接的实体框架查询

Entity Framework Query for inner join

问题是什么:

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

在实体框架中?

这就是我写的:

1
2
3
4
 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();

但这是错误的。有人能指引我走这条路吗?


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

其中db是你的DbContext。生成的查询将类似(EF6示例):

1
2
3
4
5
6
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


如果有人对方法语法感兴趣,那么如果您有导航属性,那么很容易:

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

如果不这样做,除非有一些我不知道的Join()重写,我认为它看起来相当粗糙(我是一个方法语法纯粹主义者):

1
2
3
4
5
6
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);


如果导航属性可用,则可以使用它。它在SQL中生成一个内部联接。

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