考虑以下模型:
public class News
{
public int Id { get; set; }
public string Title { get; set; }
public Branch Branch { get; set; }
public int? BranchId { get; set; }
}
public class NewsDto
{
public int Id { get; set; }
public string Title { get; set; }
public BranchDto Branch { get; set; }
}
public class Branch
{
public int Id { get; set; }
public string Name { get; set; }
public List<News> News { get; set; } = new List<News>();
}
public class BranchDto
{
public int Id { get; set; }
public string Name { get; set; }
}
我们在News
和Branch
(1对多)之间建立了可选关系。
我们发出以下查询:
context.News
.Select(dto => new NewsDto()
{
Id = dto.Id,
Title = dto.Title,
Branch = dto.Branch == null ? null : new BranchDto()
{
Id = dto.Branch.Id,
Name = dto.Branch.Name
}
}).ToList();
生成的查询是:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
CASE WHEN ([Extent2].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1],
[Extent1].[BranchId] AS [BranchId],
[Extent2].[Name] AS [Name]
FROM [dbo].[News] AS [Extent1]
LEFT OUTER JOIN [dbo].[Branches] AS [Extent2] ON [Extent1].[BranchId] = [Extent2].[Id]
它应该是这样的:在CASE WHEN
之后的左外连接处理对Branches
表的空引用。
生成相同的查询:
SELECT
[dto].[Id],
[dto].[Title],
[dto].[BranchId] IS NULL,
[dto].[BranchId],
[dto.Branch].[Name]
FROM [News] AS [dto]
INNER JOIN [Branch] AS [dto.Branch] ON [dto].[BranchId] = [dto.Branch].[Id]
我真的不明白为什么会这样。这种关系显然是可选的,因此内部联接是完全错误的。除此之外,行[dto].[BranchId] IS NULL
给出System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'IS'
,所以我猜这甚至不是有效的sql。
只有在关系是可选的时才会发生这种情况。发生了什么事?