实体框架4从实体集合中删除对象 [英] Entity Framework 4 Delete Object from entity collection

查看:219
本文介绍了实体框架4从实体集合中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个请求实体与RequestProperty实体有1 .. *关系。所以在请求中有一个RequestProperty对象的集合。当我更新请求时,我想删除RequestProperty EntityCollection中的所有项目,并从传入域对象添加新项目。当我遍历 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 OrderItems and delete each item separately. Simply removing OrderItem from collection will be executed as delete in database and clearing collection will delete all related OrderItems in database.

这篇关于实体框架4从实体集合中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆