因此,假设我有以下实体及其上下文配置设置如下。为了简洁起见,我省略了很多属性:
public class Company {
public int Id { get; set; }
public Location Location { get; set; }
}
public class Customer {
public int Id { get; set; }
public Location Location { get; set; }
}
public class Location {
public int Id { get; set; }
}
public sealed class EntityDefaultContext : DbContext {
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Company>().HasKey(m => m.Id).ToTable("Company");
modelBuilder.Entity<Company>().Property(m => m.Id).HasColumnName("Id");
modelBuilder.Entity<Company>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId"));
modelBuilder.Entity<Customer>().HasKey(m => m.Id).ToTable("Customer");
modelBuilder.Entity<Customer>().Property(m => m.Id).HasColumnName("Id");
modelBuilder.Entity<Customer>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId"));
modelBuilder.Entity<Location>().HasKey(m => m.Id).ToTable("Location");
modelBuilder.Entity<Location>().Property(m => m.Id).HasColumnName("Id");
}
}
如您所见,Company 和 Customer 实体都持有对 Location 实体的引用。我相信通常会发生的事情。
如您所见,我为此设置了数据库上下文。但是 EF 生成的 SQL 效率非常低:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[LocationId] AS [LocationId],
[Extent3].[Id] AS [Id1]
FROM
[dbo].[Customer] AS [Extent1]
LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[LocationId]
LEFT OUTER JOIN [dbo].[Company] AS [Extent3] ON [Extent1].[LocationId] = [Extent3].[LocationId]
LEFT OUTER JOIN [dbo].[Company] AS [Extent4] ON [Extent1].[LocationId] = [Extent4].[LocationId]
这是在我执行以下操作时生成的:
var q = from c in defaultContext.Set<Customer>().Include(m => m.Location)
select c;
我这样做是出于与问题无关的原因。奇怪的是,如果我只将 Location 实体配置为仅与 Customer 实体关联,那么这里是 SQL:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[LocationId] AS [LocationId]
FROM
[dbo].[Customer] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[Id]
这是我所期望的。这让我思考。EF 不支持这种情况吗?怎么可能没有?
提前致谢。