一个实体可以由超过1个实体关联吗?

时间:2012-10-22 02:15:09

标签: c# entity-framework ef-code-first entity-framework-5

因此,假设我有以下实体及其上下文配置,如下所示。为简洁起见,我省略了很多属性:

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

如您所见,公司和客户实体都持有对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不支持这种情况吗?怎么可能不是?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您的原始映射使用一对一关系。这总会导致一些特殊的行为。此外,它还有一些其他要求才能正常工作。您可能想要的是CustomerLocation以及CompanyLocation之间的一对多关系。将WithRequiredDependent更改为WithMany,它应该有效。