实体框架4实体从集合中删除对象 [英] Entity Framework 4 Delete Object from entity collection
问题描述
我有一个请求实体与1 .. *关系的RequestProperty实体。因此,有RequestProperty对象的请求的集合。当我更新请求我想删除RequestProperty EntityCollection所有项目,并从传入的域对象添加新项目。当我遍历 Request.Properties
收集和呼吁项删除或 DeleteObject的
,枚举失败,因为收藏已被修改。
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.
截至目前,我这样做:
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.
如果您定义确定的关系,你将能够为@Craig描述调用只是清除
的集合。确定关系是特殊关系,其中相关实体的主键包含母公司的外键。
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.
的例子显示了订单
实体和 OrderItem的
实体的外键确定它们之间的关系。 OrderItem的
的主键由独特的编号
和的OrderId
这为订单
表FK。有了这个配置,你不需要通过 OrderItem的
s到迭代并分别删除每个项目。只需从集合中移除 OrderItem的
将被执行在数据库中删除和清除收集将删除所有相关的 OrderItem的
S IN数据库。
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屋!