实体框架4从实体集合中删除对象

发布于 2024-10-16 08:56:21 字数 505 浏览 2 评论 0原文

我有一个与“RequestProperty”实体具有 1..* 关系的“请求”实体。所以“Request”中有一个RequestProperty对象的集合。当我更新“请求”时,我想删除 RequestProperty EntityCollection 中的所有项目,并从传入域对象中添加新项目。当我迭代 Request.Properties 集合并对该项调用删除或 DeleteObject 时,枚举失败,因为集合已被修改。

截至目前,我正在这样做:

while (true)
{
    if (newRequest.Properties.Count > 0)
        context.RequestPropertySet.DeleteObject(newRequest.Properties.First());
    else
        break;
}

由于这并不是真正的“酷”,我认为必须有另一种方法来清空关系集合。谢谢你的想法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒绊 2024-10-23 08:56:21

答案取决于您对实体进行建模的方式。如果您使用常见的独立关系或外键关系,您将必须使用当前的方法 - 我也在我的项目中使用它。

如果您定义了标识关系,您将能够按照 @Craig 的描述对集合调用 Clear 。识别关系是依赖实体的主键包含父实体的外键的特殊关系。

Example EF model

该示例显示 Order 实体和 OrderItem 实体外键标识它们之间的关系。 OrderItem的主键由唯一的IdOrderId组成,OrderIdOrder表的FK。使用此配置,您无需遍历 OrderItem 并单独删除每个项目。只需从集合中删除 OrderItem 就会像在数据库中删除一样执行,而清除集合将删除数据库中所有相关的 OrderItem

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.

Example EF model

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.

西瓜 2024-10-23 08:56:21

使用 Clear() 方法:

newRequest.Properties.Clear();

Use the Clear() method:

newRequest.Properties.Clear();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文