(1) 我是否正确地将 T-SQL 查询转换为 LINQ?
是的,你做对了。
旁注(与主要问题无关):执行时无需使用不同的名称left outer join
。一旦你使用into
子句中,用于访问实体记录的名称超出范围并且可以重用,这使得查询的其余部分看起来相似,无论连接类型如何(inner
or left outer
)。例如
join ba in Program.db.BrandAccreditations on b.ProductBrandID equals ba.ProductBrandID into bax
from credJoins in bax.DefaultIfEmpty()
could be
join ba in Program.db.BrandAccreditations on b.ProductBrandID equals ba.ProductBrandID into baJoin
from ba in baJoin.DefaultIfEmpty()
如果您删除into
以及以下内容from
线,就会变成inner join
反之亦然。
(2)当我实际上期望空值(因此左外连接)时,如何解决与空值相关的问题?
这是一个典型的错误left join
and 值类型字段。实际上完整的错误消息包含解决方案:
结果类型的通用参数或查询必须使用可空类型.
换句话说,找到来自right
的一侧left outer join
并将它们转换为可空的等价物。
对于你的情况,在这里:
select new { c.CompanyID, types.ProductTypeID, b.ProductBrandID, accreds.AccreditationID, s.AnimalName }
这些字段是types.ProductTypeID
and accreds.AccreditationID
,所以修复是(假设它们的类型int
):
select new { c.CompanyID, (int?)types.ProductTypeID, b.ProductBrandID, (int?)accreds.AccreditationID, s.AnimalName }