实体框架4从实体集合中删除对象 [英] Entity Framework 4 Delete Object from entity collection
问题描述
Request.Properties
集合并调用该项目上的一个删除或一个 DeleteObject
时,枚举失败,因为该集合已被修改。 截至目前为止,我正在这样做:
while(true)
{
if(newRequest.Properties.Count> 0)
context.RequestPropertySet.DeleteObject(newRequest.Properties.First());
else
break;
}
由于这不是真的酷,我以为必须有另一种方式清空一个关系的集合。谢谢你的想法。
答案取决于您对实体建模的方式。如果您使用常见的独立关系或外键关系,您将不得不使用现有的方法 - 我也在使用它。在我的项目中。
如果您定义了识别关系你可以在@Craig描述的集合中调用清除
。识别关系是依赖实体的主键包含父实体的外键的特殊关系。
示例显示订单
实体和 OrderItem
实体与外键识别它们之间的关系。 OrderItem
的主键由唯一的 Id
和 OrderId
组成是订单
表的FK。使用此配置,您不需要遍历 OrderItem
并分别删除每个项目。从集合中删除 OrderItem
将作为数据库中的删除执行,清除收集将删除数据库中的所有相关的 OrderItem
。
I have a "Request" Entity with an 1..* relationship to the "RequestProperty" Entity. So there's a collection of RequestProperty objects in "Request". When I update a "Request" I want to delete all items in the RequestProperty EntityCollection and add the new items from the incoming domain object. When I iterate over the Request.Properties
collection and call a remove or a DeleteObject
on the item, the enumeration fails because the collection has been modified.
As of now I'm doing this:
while (true)
{
if (newRequest.Properties.Count > 0)
context.RequestPropertySet.DeleteObject(newRequest.Properties.First());
else
break;
}
Since this is not really "cool" I thought there must be another way to empty a collection of a relationship. Thank you for your thoughts.
The answer depends on the way you modeled your entities. If you are using common independent relation or foreign key relation you will have to use your current approach - I'm using it as well in my project.
If you defined identifying relation you will be able to call just Clear
on collection as @Craig described. Identifying relation is special relation where primary key of dependent entity contains foreign key of parent entity.
The example shows Order
entity and OrderItem
entity with foreign key identifying relation between them. Primary key of OrderItem
consists of unique Id
and OrderId
which is FK of Order
table. With this configuration you don't need to iterate through OrderItem
s and delete each item separately. Simply removing OrderItem
from collection will be executed as delete in database and clearing collection will delete all related OrderItem
s in database.
这篇关于实体框架4从实体集合中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!