问题
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,
- I can Insert in BaseDbSet.
- I can Delete from BaseDbSet.
- Deleting from DerivedDbSet deletes only the Derived Entity.
- 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