内部连接的entity framework查询
什么是查询:
select s.* from Service s inner join ServiceAssignment sa on sa.ServiceId = s.Id where sa.LocationId = 1
在entity framework?
这是我写的:
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();
但是这是错误的。 有人能引导我走上这条道路吗?
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样本):
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
如果任何人对Method语法感兴趣,如果你有一个导航属性,这是很容易的:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
如果你不这样做,除非有一些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);
如果可用,可以使用导航属性。 它在SQL中产生一个内部连接。
from s in db.Services where s.ServiceAssignment.LocationId == 1 select s