Developex
Developex

Reputation: 328

Cascade delete in entity framework ( table per type inheritance )

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 A2. B and C has associations(1 to many, with OnDelete action on the DB side) to A1 and A2 respectively.

Problem

I trying to delete record from B, so I expect that EF remove also all A1 objects which associated to current B's record.

In the end, EF remove record from B and all associated records from A1, but not from A

Why? how fix it?

Upvotes: 13

Views: 5947

Answers (2)

naskew
naskew

Reputation: 2151

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.

Upvotes: 0

Slauma
Slauma

Reputation: 177163

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

Upvotes: 7

Related Questions