Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...