简体   繁体   English

EntityFramework TPT继承

[英]EntityFramework TPT inheritance

I have a simple TPT Inheritance, EF 6.1.1 我有一个简单的TPT继承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 . 请注意,在我的情况下, Base不是抽象类,因为在我的域中可以存在Base的实例,而没有Derived DbContext : 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. 我可以插入BaseDbSet中。
  2. I can Delete from BaseDbSet. 我可以从BaseDbSet中删除。
  3. Deleting from DerivedDbSet deletes only the Derived Entity. 从DerivedDbSet删除仅删除派生实体。
  4. Inserting in the DerivedDbSet insert also a new record in the Base Table, also if the Id is correct, creating a new Id. 如果ID正确,则在DerivedDbSet中插入一个新记录,也将在基表中插入一个新记录,从而创建一个新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? 我真的不明白第4点。如何在未在Base表中插入新记录的情况下在派生表中插入记录? 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. 似乎在插入EF时并不在意Derived类的ID,因为Id属性具有HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) ,但是我无法在Base和Derived类中指定其他DatabaseGeneratedOption属性。

It is the expected behaviour. 这是预期的行为。 A Derived entity can not exist without Base entity. 没有Base实体就无法存在Derived实体。

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. 如果要插入不在Base表中的IdDerived实体,则EF在BaseDerived插入一个新的元组,在Base表中写Id ,在Derived表中写SomeProperty 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. 如果您要尝试的是从现有Base创建Derived ,只需点击此链接并阅读一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM