TPH继承在实体框架代码中没有按预期工作

时间:2016-03-31 06:52:45

标签: c# entity-framework inheritance ef-code-first entity-framework-6

我有以下抽象类:

public abstract class Address
{
    public string Street { get; set; }
}

然后我直接从它继承:

public class CustomerAddress : Address
{
    public int CustomerId { get; set; }
}

public abstract class CompanyAddressBase : Address
{ }

public class MainOfficeAddress : CompanyAddressBase
{
    public int MainOfficeId { get; set; }
}

public class SubsidiaryAddress : CompanyAddressBase
{
    public int SubsidiaryId { get; set; }
}

映射如下:

public class CustomerAddressMap : EntityTypeConfiguration<CustomerAddress>
{
    public CustomerAddressMap() 
    {
        this.ToTable("CustomerAddresses");
        //Properties here...
    }
}

public class CompanyAddressBaseMap : EntityTypeConfiguration<CompanyAddressBase>
{
    public CompanyAddressBaseMap() 
    {
        this.ToTable("CompanyAddresses");

        this.Map<MainOfficeAddress>(m => m.Requires("type")
            .HasValue((int)CompanyType.MainOffice)
            .IsRequired());

        this.Map<SubsidiaryAddress>(m => m.Requires("type")
            .HasValue((int)CompanyType.Subsidiary)
            .IsRequired());
    }
}

public class MainOfficeAddressMap : EntityTypeConfiguration<MainOfficeAddress>
{
    public MainOfficeAddressMap ()
    {
        this.Property(t => t.MainOfficeId).HasColumnName("companyId")
            .IsRequired();
    }
}

public class SubsidiaryAddressMap : EntityTypeConfiguration<SubsidiaryAddress>
{
    public SubsidiaryAddressMap ()
    {
        this.Property(t => t.SubsidiaryId).HasColumnName("companyId")
            .IsRequired();
    }
}

注册DbSets

public DbSet<CompanyAddressBase> CompanyAddresses { get; set; }
public DbSet<CustomerAddress> CustomerAddresses { get; set; }

modelBuilder.Configurations.Add(new CompanyAddressBaseMap());
modelBuilder.Configurations.Add(new MainOfficeAddressMap());
modelBuilder.Configurations.Add(new SubsidiaryAddressMap());
modelBuilder.Configurations.Add(new CustomerAddressMap());

但是,当我尝试保存公司地址(即主办公室或子公司)时,会抛出异常:

  

dbo.Addresses not found

以上不是TPH的正确配置吗?我错过了什么吗?

0 个答案:

没有答案