c# - 左外连接不被尊重
问题描述
我们有以下 EF 代码:
var qry =
from c in db.Contacts
join comp in db.Companies on c.CompanyId equals comp.CompanyId
into compLeft
from cj in compLeft.DefaultIfEmpty()
select new CompleteUserDlModel
{
CompanyName = cj.Company1,
CompanyId = c.CompanyId
};
生成此 SQL
SELECT
[Extent1].[CompanyId] AS [CompanyId],
[Extent2].[Company] AS [Company]
FROM [dbo].[Contacts] AS [Extent1]
INNER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[CompanyId] = [Extent2].[CompanyId]
但我们实际上想要
SELECT
[Extent1].[CompanyId] AS [CompanyId],
[Extent2].[Company] AS [Company]
FROM [dbo].[Contacts] AS [Extent1]
LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[CompanyId] = [Extent2].[CompanyId]
有人能指出我们做错了什么吗?
C# EF 中左外连接的所有引用(即LINQ 中的 LEFT OUTER JOIN)都指向我们正在使用的语法。显然,我们遗漏了一些东西。
解决方案
Could someone point out what we've done wrong, please?
Probably you have Contact.CompanyId
a typed as int
instead of int?
, making it a required property, and so EF assumes you have referential integrity when generating a query.
But, as always, left join
in LINQ has bad code smell, and can almost always be replaced by just querying your target entity and traversing its Navigation Properties. EG:
from c in db.Contacts
select new
{
CompanyName = c.CompanyId.HasValue?c.Company.CompanyName : null,
CompanyId = c.CompanyId
};
推荐阅读
- javascript - 如何清除静态资产上的缓存
- mysql - 将所有临时(别名)列结果添加到 TMemo
- css - 当我将 toggleclassList('open) 放在我的 .sidebar 类上时,转换属性不会只在 .sidebar 上起作用 为什么它不起作用?
- swift - URL 不断返回 nil
- selenium-webdriver - Selenium:@FindBy 注解和 initElemets() 方法
- node.js - 我想将 IBM 的 Chatbot 与我的电子和 nodejs 集成
- android - 如何观察参考变量?
- asp.net-mvc - EditorFor只能输入时间,不能设置24小时格式
- css - 如何创建指令以在其他指令在 Angular 中发生之前删除它们
- javascript - 有些方法如何在原型中但不能通过 Object.assign 传递,而其他一些方法是