EF6 - 当抽象基类具有其他实体的外键时,TPC继承失败

时间:2017-12-15 17:46:44

标签: c# .net inheritance orm entity-framework-6

非常感谢您提前,

我有一个名为Person的抽象类,它有一个City表的外键。

public abstract class Person
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("id")]
    public Int32 Id { get; set; }

    [Column("city")]
    public int CityId { get; set; }
    [Required]
    [ForeignKey("CityId")]
    public City City
    {
        get; set;
    }
}

    [Table("cities", Schema = "public")]
    [Serializable]
    public class City 
    {
        public City()
        {
        }

        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Key]
        [Column("id")]
        public Int32 Id { get; set; }

        [Column("name")]
        public String Name { get; set; }
    }

之后我的Customer类继承自Person

public class Customer:Person
{
    [Column("cpfcnpj")]
    public String CpfCnpj { get; set; }
}

我正在我的上下文类中映射TPC (Type per Concrete)继承:

public class MyContext:DbContext
{
    public DbSet<Person> People { get; set; }

    public MyContext():base("MyConnection")
    {
        Configuration.LazyLoadingEnabled = false;   
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Conventions.Remove();

        modelBuilder.Entity<Customer>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("customers", "public");
        });

        base.OnModelCreating(modelBuilder);
    }
}

当我尝试拿起customers时,我收到以下错误:

  

Person :: End'Sant'引用的EntitySet'Pers'不能   可以在包含EntityContainer中找到。

用于选择客户的代码如下:

using (var context = new MyContext())
{
     //get error in this line
     var customers = context.People.OfType<Customer>().ToList();

    //...
}

注意:为了测试,我传递了foreign key具体类的Customer属性并完美执行。

有人能帮助我吗?我真的需要了解这种情况。

感谢。

0 个答案:

没有答案