本文介绍了Cascade在实体框架中删除(每个类型继承的表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有DB模型,每个类型继承表。
例如,实体是A,B,C,A1,A2。
Base - A
派生 - A1,A2。
另一个 - B,C.
所以A与A1和A2有1到1个关联。
B和C分别具有关联(1到多个,在DB侧具有OnDelete动作)到A1和A2。



问题



我试图从B删除记录,所以我期望EF删除与当前B记录相关联的所有A1对象。



最后,EF从A1删除记录,并从A1中删除所有关联的记录,但不从A



为什么?如何修复?

解决方案

这是一个已知的问题,我会称之为错误。显然,从派生实体属性的表 A1 中删除​​记录是不正确的。数据库中的剩余数据(表 A )确实表示另一个对象类型。换句话说:这个DELETE实际上没有删除一个实体,但是它改变了实体的type =将类型为 A1 的对象转换为类型为的对象一个 - 如果 A 是一个抽象实体,这样就更不用说了。



推荐的解决方法从(据我所知)丑陋:

  var b = context.Bs.Include(A1s)。单(b => b.Id == 1); 
foreach(ba.A1s.ToList()中的var a1)
context.As.Remove(a1);
context.Bs.Remove(b);
context.SaveChanges();

context.As.Remove(a1); 应该从 A A1 表中删除,从而将孤立记录的问题修复到表 A 。不幸的是,您被迫从数据库中加载孩子,以正确地删除父母。



这是另一个有关此问题的问题和解答:


I have DB model with table per type inheritance.For example, entities are A, B, C, A1, A2.Base - ADerived - 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?

解决方案

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

这篇关于Cascade在实体框架中删除(每个类型继承的表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 01:02