实体框架在应该进行INNER JOIN时生成LEFT OUTER JOIN(多个表)

时间:2011-09-20 11:17:06

标签: c# linq entity-framework

我有以下奇怪的行为:

public class Result
{
    [Key]
    public int Id { get; set; }
    public int RuleId { get; set; }
    public int UserId { get; set; }

    [ForeignKey("RuleId")]
    public virtual Rule Rule { get; set; }

    [ForeignKey("UserId ")]
    public virtual User User { get; set; }
}

public class Rule
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    // More columns
}

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    // More columns
}

如果我这样做:

ctx.Results.AsQueryable().Select(r => new { r.Rule.Name } ).ToList();

在SQL Server中执行的查询在Rule:

上执行内部联接
SELECT 
[Extent1].[RuleId] AS [RuleId], 
[Extent2].[Name] AS [Name]
FROM  [dbo].[result] AS [Extent1]
INNER JOIN [dbo].[rule] AS [Extent2] ON [Extent1].[RuleId] = [Extent2].[Id]

BUT 如果我这样做:

ctx.Results.AsQueryable().Select(r => new { rn = r.Rule.Name, un = r.User.Name } ).ToList();

执行的查询在规则上执行内连接,但在用户上执行OUTER JOIN。

SELECT 
[Extent1].[UserId] AS [UserId], 
[Extent2].[Name] AS [Name], 
[Extent3].[Name] AS [Name1]
FROM   [dbo].[result] AS [Extent1]
INNER JOIN [dbo].[rule] AS [Extent2] ON [Extent1].[RuleId] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[user] AS [Extent3] ON [Extent1].[UserId] = [Extent3].[Id]

当然这是错的?

1 个答案:

答案 0 :(得分:4)

答案是:实体框架中的错误。下载最新版本,它们都是内部联接。