EntityFramework TPT inheritance

a 夏天 提交于 2021-02-07 10:19:53

问题


I have a simple TPT Inheritance, EF 6.1.1

public class Base {
    public int Id {get; set;}
}

public class Derived : Base {
     public int SomeProperty {get; set;}
}

Note that in my case Base is NOT an abstract class, because in my domain can exists an instance of Base without Derived. DbContext :

public class ApplicationDbContext : DbContext {

   protected override void OnModelCreating(DbModelBuilder modelBuilder) {
       base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Derived >().ToTable("Derived");
   }

   public DbSet<Base> BaseDbSet {get ; set; }
   public DbSet<Derived> DerivedDbSet {get ; set; }
}

Now,

  1. I can Insert in BaseDbSet.
  2. I can Delete from BaseDbSet.
  3. Deleting from DerivedDbSet deletes only the Derived Entity.
  4. Inserting in the DerivedDbSet insert also a new record in the Base Table, also if the Id is correct, creating a new Id.

I really don't understand point 4. How can I insert a record in the derived table without inserting a new one in the Base table? I think the problem was related to identity column. It seems that when inserting EF doesn't care the Id of the Derived class, because the Id property has HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity), but I cannot specify different DatabaseGeneratedOption attribute in Base and Derived class.


回答1:


It is the expected behaviour. A Derived entity can not exist without Base entity.

If you are inserting a Derived entity wich Id is not in Base table, EF insert a new tuple in Base and in Derived, writing Id in Base table and SomeProperty in Derived table. Any other behavior produce data corruption and inconsistency.

If what you are trying is create a Derived from a existing Base just follow this link and read a bit.



来源:https://stackoverflow.com/questions/26036436/entityframework-tpt-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!