Cascade delete in entity framework ( table per type inheritance )

后端 未结 2 2037
囚心锁ツ
囚心锁ツ 2020-12-05 20:01

I have DB model with table per type inheritance. For example, entities are A, B, C, A1, A2. Base - A Derived - A1, A2. Another - B, C. So, A has 1 to 1 association to A1 and

相关标签:
2条回答
  • 2020-12-05 20:21

    It's a known problem and I would call it a bug. Obviously only deleting the records from the table A1 for the derived entity's properties cannot be correct. The remaining data in the database (in table A) do represent another object type. In other words: This DELETE didn't actually delete an entity but it changed the entity's type = transformed an object of type A1 into an object of type A - which makes even less sense if A is an abstract entity.

    The recommended workaround from here (as I understand it) is ugly:

    var b = context.Bs.Include("A1s").Single(b => b.Id == 1);
    foreach (var a1 in b.A1s.ToList())
        context.As.Remove(a1);
    context.Bs.Remove(b);
    context.SaveChanges();
    

    context.As.Remove(a1); should delete from both A and A1 table, thereby fixing the problem of the orphaned records in table A. Unfortunately you are forced to load the children from the database to delete the parent correctly.

    Here is another question and answer about this problem: Problems using TPT (Table Per Type) in EF 4.2 and deletion of parent objects

    0 讨论(0)
  • 2020-12-05 20:29

    I had the same problem and a colleague told me to iterate over the collection of items before doing Remove(o) and suddenly it all worked.

    0 讨论(0)
提交回复
热议问题