EntityFramework TPT继承 [英] EntityFramework TPT inheritance
问题描述
我有一个简单的TPT继承EF 6.1.1
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;}
}
请注意,在我的情况下, Base
不是抽象类,因为在我的域中可以存在没有 Derived
的 Base
实例.DbContext:
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; }
}
现在,
- 我可以插入BaseDbSet中.
- 我可以从BaseDbSet中删除.
- 从DerivedDbSet中删除仅删除派生实体".
- 在DerivedDbSet中插入还在基表中插入一条新记录,如果Id正确,也会创建一个新Id.
我真的不明白第4点.如何在未在Base表中插入新记录的情况下在派生表中插入记录?我认为问题与身份列有关.似乎在插入EF时并不在意Derived类的ID,因为Id属性具有 HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
,但是我无法在Base和Derived类中指定其他DatabaseGeneratedOption属性.
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.
推荐答案
这是预期的行为.没有 Base
实体,就不能存在 Derived
实体.
It is the expected behaviour. A Derived
entity can not exist without Base
entity.
如果要在 Base
表中未插入 Id
的 Derived
实体,则EF在 Base
并在 Derived
中,在基本表中写入 Id
,在 Derived
表中写入 SomeProperty
.任何其他行为都会导致数据损坏和不一致.
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.
这篇关于EntityFramework TPT继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!