EF7生成带有可选关系的错误sql

时间:2016-01-03 10:38:56

标签: asp.net sql-server entity-framework-core

考虑以下模型:

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; }
}

我们在NewsBranch(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();

EF6

生成的查询是:

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表的空引用。

EF7(RC1)

生成相同的查询:

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。

只有在关系是可选的时才会发生这种情况。发生了什么事?

1 个答案:

答案 0 :(得分:0)

所以我认为这与issue #3186有关。 EF团队认为这是一个高优先级的错误,应该在RC2中修复。