我有一个关于 LINQ2SQL 查询生成的 SQL 语句的问题。我有两个数据库表(VisibleForDepartmentId
是外键):
AssignableObject Department
---------------------- ------------
AssignableObjectId ┌────> DepartmentId
AssignableObjectType │
VisibleForDepartmentId ───┘
以及以下映射信息(注意AssignableObject
是抽象的):
<Database Name="SO_755661" Class="DataClassesDataContext">
<Table Name="dbo.AssignableObject" Member="AssignableObjects">
<Type Name="AssignableObject" Modifier="Abstract">
<Column Name="AssignableObjectId" Type="System.Int32"
DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true"
IsDbGenerated="true" CanBeNull="false" />
<Column Name="AssignableObjectType" Type="System.String"
DbType="VarChar(50) NOT NULL" CanBeNull="false"
AccessModifier="Private" IsDiscriminator="true"/>
<Column Name="VisibleForDepartmentId" Type="System.Int32"
DbType="Int" CanBeNull="true" />
<Association Name="Department_AssignableObject" Member="VisibleForDepartment"
ThisKey="VisibleForDepartmentId" OtherKey="DepartmentId"
Type="Department" IsForeignKey="true" />
<Type Name="Asset" InheritanceCode="Asset" IsInheritanceDefault="true" />
<Type Name="Role" InheritanceCode="Role" />
</Type>
</Table>
<Table Name="dbo.Department" Member="Departments">
<Type Name="Department">
<Column Name="DepartmentId" Type="System.Int32"
DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true"
IsDbGenerated="true" CanBeNull="false" />
<Column Name="Name" Type="System.String" DbType="VarChar(50) NOT NULL"
CanBeNull="false" />
<Association Name="Department_AssignableObject" Member="AssignableObjects"
ThisKey="DepartmentId" OtherKey="VisibleForDepartmentId"
Type="AssignableObject" />
</Type>
</Table>
</Database>
以及以下代码:
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Asset>(a => a.VisibleForDepartment);
dataContext.LoadOptions = loadOptions;
var assets = from a in dataContext.Assets
select a;
这会产生一个带有两个相同左外连接的 SQL 查询:
SELECT t0.AssignableObjectType, t0.AssignableObjectId, t0.VisibleForDepartmentId,
t2.test, t2.DepartmentId, t2.Name, t4.test AS test2,
t4.DepartmentId AS DepartmentId2, t4.Name AS Name2
FROM dbo.AssignableObject AS t0
LEFT OUTER JOIN (
SELECT 1 AS test, t1.DepartmentId, t1.Name
FROM dbo.Department AS t1
) AS t2 ON t2.DepartmentId = t0.VisibleForDepartmentId
LEFT OUTER JOIN (
SELECT 1 AS test, t3.DepartmentId, t3.Name
FROM dbo.Department AS t3
) AS t4 ON t4.DepartmentId = t0.VisibleForDepartmentId
为什么有两个外连接,一个就足够了?
亲切的问候,
罗纳德