实体框架无法映射类之间的关系

时间:2014-05-13 15:22:48

标签: entity-framework inheritance mapping table-per-class

我经历过很多帖子,但从来没有发现类似我的问题

出于某种原因,我无法在使用EF Code First创建数据库时正确映射类之间的关系

这些类是 - 订单抽象类

public abstract class Order : IObjectWithState
{
    public int OrderId { get; set; }

    public OrderType Type { get; set; }
    public string Status { get; set; }

    [NotMapped]
    public State ObjectState { get; set; }

    public string CustomerId { get; set; }
}

实现它的两个类:

public class SampleOrder : Order
{
    public DateTime CreationDate { get; set; }
    public DateTime CompletionDate { get; set; }

    public virtual ICollection<OrderItem> OrderItems { get; set; }
    public virtual Address BillAddress { get; set; }
}

public class HideOrder : Order
{
    public DateTime CreationDate { get; set; }
    public DateTime CompletionDate { get; set; }
    public bool Paid { get; set; }

    public virtual ICollection<OrderItem> OrderItems { get; set; }
    public virtual Address BillAddress { get; set; }
}

这是地址类:

public class Address : IObjectWithState
{
    public int AddressId { get; set; }

    public string AddressLine { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
    public bool Main { get; set; }
    public string CustomerId { get; set; }

    [NotMapped]
    public State ObjectState { get; set; }
}

我的上下文类看起来像这样:

public PhoeniceContext() : base("Phoenice")
{
}

public DbSet<Address> Addresses { get; set; }
public DbSet<SampleOrder> SampleOrders { get; set; }
public DbSet<HideOrder> HideOrders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SampleOrder>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("SampleOrders");
    });

    modelBuilder.Entity<HideOrder>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("HideOrders");
    });
}

当我尝试创建数据库时,我收到错误消息:

  

协会&#39; SampleOrder_BillAddress&#39;实体类型之间   &#39; SampleOrder&#39;和&#39;地址&#39;是无效的。在TPC层次结构中独立   仅在大多数派生类型上允许关联。

如果我从两个订单类中注释掉BillAddress属性,则映射到OrderItems的行为正确。为什么映射到地址项也不起作用?

0 个答案:

没有答案