在一对多关系中,EF LEFT OUTER JOIN而不是INNER JOIN

时间:2015-05-12 15:02:35

标签: sql-server linq entity-framework join linq-to-sql

我有以下EF代码优先模型

public class A
{
    public int Id { get; set; }
    public B B { get; set; }
}

public class B
{
    public int Id { get; set; }
    public string Text { get; set; }
}

这些映射

modelBuilder.Entity<A>()
     .HasOptional(a => a.B)
     .WithMany();

modelBuilder.Entity<B>()
     .HasKey(b => b.Id);

当我运行此查询时:

context.As.Include(a => a.B).FirstOrDefault();

导致以下sql:

SELECT TOP (1) 
    [Extent1].[Id] AS [Id], 
    [Extent2].[Id] AS [Id1], 
    [Extent2].[Text] AS [Text]
FROM  [dbo].[A] AS [Extent1]
LEFT OUTER JOIN [dbo].[B] AS [Extent2] ON [Extent1].[B_Id] = [Extent2].[Id]

我期待得到INNER JOIN而不是LEFT OUTER JOIN

1 个答案:

答案 0 :(得分:3)

它仍将返回A表中的所有数据,并且不依赖于从B表返回的任何内容。另一方面,您将只包含B表中与A表有关联的元素,因为这是您的开始。

或显示this image from W3Schools

enter image description here