EntityCollection Clear()和Remove()方法 [英] EntityCollection Clear() and Remove() methods

查看:609
本文介绍了EntityCollection Clear()和Remove()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除EF实体的所有收集项目的正确方法是什么?在下面的代码中,DocumentItems是文档的相关文档项目的集合。此代码继续执行Clear(),但在SaveChanges()上失败,因为相关项目通过FK连接到其文档,FK是强制性的。所以我猜他们在Clear()之后,不用外键就会浮在空中。

What is the right way to delete all of the collection items of an EF entity? In the code below, DocumentItems is the collection of related document items for a document. This code proceedes on Clear() but fails on SaveChanges() because related items are connected to their document via FK and FK is mandatory. So I guess they somehow remain floating up in the air without a foreign key after Clear().

我是否通过在每个项目上调用Remove()的集合的foreach循环来解决这个问题,还是有其他方式?

Do I solve this with a foreach loop over the collection calling Remove() on each item or is there another way?

// remove existing document items to prepare for refreshing them
existing.DocumentItems.Clear();
// adds new Document Items
PrepareInvoice(existing, collection);
_repository.SaveChanges();


推荐答案

这是删除集合中的项目的一种方法。

This is one way of deleting the items in the collection.

VB

TEntityCollection.ToList().ForEach(Sub(o) ctx.DeleteObject(o))

C#

TEntityCollection.ToList().ForEach(x => ctx.DeleteObject(x))

然后你需要调用

ctx.SaveChanges()

这篇关于EntityCollection Clear()和Remove()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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