3

看了很多帖子,没发现和我一样的问题

出于某种原因,在使用 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");
    });
}

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

实体类型“SampleOrder”和“Address”之间的关联“SampleOrder_BillAddress”无效。在 TPC 层次结构中,仅在最派生的类型上允许独立关联。

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

4

0 回答 0