C# · 12月 30, 2021

c#-4.0 – 实体框架和强制内部加入

我有Table1具有以下关系(它们不被强制,它们只为导航属性创建关系) Table1 (*)->(1) Table2Table1 (*)->(1) Table3Table1 (*)->(1) Table4Table1 (*)->(1) Table5

使用热切的加载代码看起来像

IQueryable<Table1> query = context.Table1s;query = query.Include(Table1 => Table1.Table2);query = query.Include(Table1 => Table1.Table3);query = query.Include(Table1 => Table1.Table4);query = query.Include(Table1 => Table1.Table5);query = query.Where(row => row.Table1Id == table1Id);query.Single();

我尝试组织Include()语句的方式,包含的第一个表在其生成的Tsql中有一个Inner Join,其余的是Left Outer Join(我希望所有的都是Left Outer).我不是实体拆分,他们只是简单的FK表.

如果DefaultIfEmpty()是唯一的解决方案,有人可以解释为什么除了第一个表之外的所有提供sql预期的原因?

我的理解是,导航属性的默认行为是LEFT OUTER,但是我无法获取所有属性以生成默认值.

任何帮助将不胜感激.

先谢谢你!

—–创建Tsql(为了简洁而修改但结构相同)——-

(@p__linq__0 int)SELECT [Limit1].[Table1Id] AS [Table1Id],[Limit1].[OtherData] AS [OtherData]FROM ( SELECT TOP (2) [Extent1].[Table1Id] AS [Table1Id],[Extent1].[OtherData] As [OtherData] FROM [dbo].[Table1] AS [Extent1] INNER JOIN [dbo].[Table2] AS [Extent2] ON [Extent1].[Table2Id] = [Extent2].[Table2Id] LEFT OUTER JOIN [dbo].[Table3] AS [Extent3] ON [Extent1].[Table3Id] = [Extent3].[Table3Id] LEFT OUTER JOIN [dbo].[Table4] AS [Extent4] ON [Extent1].[Table4Id] = [Extent4].[Table4Id] LEFT OUTER JOIN [dbo].[Table5] AS [Extent5] ON [Extent1].[Table5Id] = [Extent5].[Table5Id] WHERE [Extent1].[Table1Id] = @p__linq__0) AS [Limit1]解决方法 在EF中,当执行IQueryable.Include()时,如果没有一个导航属性是基于强制关系,则EF将使用第一个表.它期望至少有一个关系在模式中被强制执行,并且应该使用IQueryable.Include()进行编码,然后使用Include()添加其他表,