实体框架4从实体集合中删除对象
我有一个与“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案取决于您对实体进行建模的方式。如果您使用常见的独立关系或外键关系,您将必须使用当前的方法 - 我也在我的项目中使用它。
如果您定义了标识关系,您将能够按照 @Craig 的描述对集合调用
Clear
。识别关系是依赖实体的主键包含父实体的外键的特殊关系。该示例显示
Order
实体和OrderItem
实体外键标识它们之间的关系。OrderItem
的主键由唯一的Id
和OrderId
组成,OrderId
是Order
表的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.The example shows
Order
entity andOrderItem
entity with foreign key identifying relation between them. Primary key ofOrderItem
consists of uniqueId
andOrderId
which is FK ofOrder
table. With this configuration you don't need to iterate throughOrderItem
s and delete each item separately. Simply removingOrderItem
from collection will be executed as delete in database and clearing collection will delete all relatedOrderItem
s in database.使用
Clear()
方法:Use the
Clear()
method: