LINQ查询
from rc in context.RC
join r in context.R on rc.RId equals r.Id
join c in context.C on rc.CId equals c.Id
join f in context.F on rc.FId equals f.Id into fg
from f in fg.DefaultIfEmpty()
join e in context.E on rc.EId equals e.Id into eg
from e in eg.DefaultIfEmpty()
生成的SQL
SELECT *
FROM [dbo].[RC] AS [Extent1]
INNER JOIN [dbo].[R] AS [Extent2] ON [Extent1].[RId] = [Extent2].[Id]
INNER JOIN [dbo].[C] AS [Extent3] ON [Extent1].[CId] = [Extent3].[Id]
INNER JOIN [dbo].[F] AS [Extent4] ON [Extent1].[FId] = [Extent4].[Id]
INNER JOIN [dbo].[E] AS [Extent5] ON [Extent1].[EId] = [Extent5].[Id]
我想要的是
SELECT *
FROM [dbo].[RC] AS [Extent1]
INNER JOIN [dbo].[R] AS [Extent2] ON [Extent1].[RId] = [Extent2].[Id]
INNER JOIN [dbo].[C] AS [Extent3] ON [Extent1].[CId] = [Extent3].[Id]
LEFT JOIN [dbo].[F] AS [Extent4] ON [Extent1].[FId] = [Extent4].[Id]
LEFT JOIN [dbo].[E] AS [Extent5] ON [Extent1].[EId] = [Extent5].[Id]
不确定我的LINQ查询中缺少什么
代码的屏幕截图
更新
基于@GertArnold的评论,RC-F
(表格)和RC-E
(表格)位于N-1
关联中,其中RC
应包含有效的ID密钥参考F
,但在RC
表格中,有些F
ID为零,我在执行inner join
时会跳过数据。
那么现在如何在不修改我的数据库架构的情况下强制Entity-Framework / LINQ生成LEFT JOIN
语法
答案 0 :(得分:0)
基于@GertArnold的评论,RC-F(表格)和RC-E(表格)处于N-1关联,其中RC应该为F保存有效的id键参考,但在RC表中,有些F ID是零,在我进行内连接时跳过数据。
这就是我最终查询结果的方式。
List<MyType> myResults;
using (Entities context = new Entities())
{
var results = (from rc in context.RC
join r in context.R on rc.RId equals r.Id
join c in context.C on rc.CId equals c.Id
select rc).ToList();
myResults = results.Select(rc => new MyType
{
Id = rc.Id,
Rule = new IdName
{
Id = rc.R.Id,
Name = rc.R.Name
},
Conjuction = new IdName
{
Id = rc.C.Id,
Name = rc.C.Conjuncation
},
Field = new IdName
{
Id = rc.F!= null ? rc.F.Id : 0,
Name = rc.F!= null ? rc.F.Name : null
},
Expression = new IdName
{
Id = rc.E!= null ? rc.E.Id : 0,
Name = rc.E!= null ? rc.E.Expression : null
},
DisplayOrder = rc.Order,
Value1 = rc.Value,
Value2 = rc.Value2
}).ToList();
}