[英]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, 现在,
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
表中的Id
的Derived
实体,则EF在Base
和Derived
插入一个新的元组,在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.