开发者

Entity Framework generating LEFT OUTER JOINs when it should be doing INNER JOINs (multiple tables)

I have the following weird behaviour:

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
}

If I do:

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

The query executed in SQL Server does an inner join on 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 if I do:

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

The query executed does an inner join on rule but an OUTER JOIN on User.

SELECT 
[Extent1].[UserId] AS [UserId], 
[Extent2].[Name] AS 开发者_C百科[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]

Surely this is wrong?


Answer was: Bug in entity framework. Download very latest version and they are all inner joins.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜