实体框架 - 清除子集 [英] Entity Framework - Clear a Child Collection
问题描述
我遇到了一个有趣的问题,实体框架,并基于我不得不用来解决它的代码,我怀疑我的解决方案不太理想。表A和表B之间有一对多关系,表B中的实体参考了表A。我有一个场景,我想同时删除TableA中的所有孩子,我认为这可以通过简单地清除集合来实现:
I have run into an interesting problem with Entity Framework and based on the code I had to use to tackle it I suspect my solution is less than ideal. I have a 1-to-Many relationship between Table A and Table B where entities in TableB have a reference to TableA. I have a scenario where I want to simultaneously delete all children of a row in TableA and I thought this could be achieve by simply clearing the collection:
Entity.Children.Clear()
不幸的是,当我尝试保存更改时作为外键违规。
Unfortunately, when I attempted to save changes this produced as a Foreign Key violation.
正在添加关系或
从AssociationSet
'FK_EntityB_EntityA'中删除。使用基数
约束,还必须添加或删除相应的EntityB
。
A relationship is being added or deleted from an AssociationSet 'FK_EntityB_EntityA'. With cardinality constraints, a corresponding 'EntityB' must also be added or deleted.
解决方案想出来的是通过实体上下文的DeleteObject()手动删除对象,但是我只是知道我使用的这个逻辑一定是错误的。
The solution I came up with was to manually delete object via the entity context's DeleteObject(), but I just know this logic I am using has got to be wrong.
while (collection.Any())
Entities.DeleteObject(collection.First());
对于一个,我不得不使用Where()循环的事实远远不及理想,但我认为这纯粹是我的语义评估。在任何情况下,我正在做这些事情是否有问题,或者是否有更好的方法来清除实体的子实体集合,以便Entity Framework在所有被删除的对象上正确地调用数据存储删除? p>
For one, the fact that I had to use a Where() loop seems far less than ideal, but I suppose that's purely a semantic assessment on my part. In any case, is there something wrong with how I am doing this, or is there perhaps a better way to clear a child entity collection of an entity such that Entity Framework properly calls a data store delete on all of the removed objects?
推荐答案
Clear()
删除引用实体,而不是实体本身。
Clear()
removes the reference to the entity, not the entity itself.
如果您打算这样执行相同的操作,您可以处理 AssociationChanged
:
If you intend this to be always the same operation, you could handle AssociationChanged
:
Entity.Children.AssociationChanged +=
new CollectionChangeEventHandler(EntityChildrenChanged);
Entity.Children.Clear();
private void EntityChildrenChanged(object sender,
CollectionChangeEventArgs e)
{
// Check for a related reference being removed.
if (e.Action == CollectionChangeAction.Remove)
{
Context.DeleteObject(e.Element);
}
}
您可以使用部分课程。
这篇关于实体框架 - 清除子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!