EntityFramework TPT继承 [英] EntityFramework TPT inheritance

查看:36
本文介绍了EntityFramework TPT继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的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; }
}

现在,

  1. 我可以插入BaseDbSet中.
  2. 我可以从BaseDbSet中删除.
  3. 从DerivedDbSet中删除仅删除派生实体".
  4. 在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.

如果您要尝试的是从现有的 Base 创建派生的,只需遵循此

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

这篇关于EntityFramework TPT继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆