实体框架一对多关系保存问题

发布于 2024-09-11 14:23:17 字数 566 浏览 1 评论 0原文

我一直在挖掘这里和谷歌上的帖子,但找不到任何可以帮助我解决在现有实体上保存子实体的问题的内容。

假设我有一个可以容纳物品的购物车,这意味着我有一个 ShoppingCart 实体,其中包含 ShoppingCartItem 实体集合。

在我的控制器中,我检查 ShoppingCart 是否存在并检索实体(如果存在)。如果没有,则它是一个新实体(Entitystate 标记为“已添加”)。 然后,我继续将项目添加到已经存在的集合中(如果其中已有任何项目) 我现在的问题是仅当我将更改保存到已创建的购物车时: 它在数据库中添加一个新的购物车,其中包含现有商品和新商品...

因此,如果我有一个 Shoppingcart 和两个子商品,现在我添加 3 个新商品,那么我最终会在 ShoppingCart 表中得到 2 个 ShoppingCart 条目和 7 个 ShoppingCartItem 条目...

我跟踪了代码,一旦使用 AddObject() 添加新的 ShoppingCartItem,ShoppingCart 实体就会被标记为“已添加”...

我该如何防止这种情况发生?

非常感谢,

斯蒂芬

I've been digging in the posts in here and on google and couldn't find anything helping me to solve a problem I have with saving children entities on an existing entity.

Let's say I have a shopping cart that will hold items, that means I have a ShoppingCart entity which has ShoppingCartItem entity collection.

In my controller, I check if the ShoppingCart exists and retrieve the entity if there's one. If not, it's a new entity (Entitystate is marked as Added).
Then, I continue by adding items to the already existing collection (if any items are in there already)
My problem right now is ONLY when I save changes to an already created ShoppingCart:
It's adding a NEW Shopping cart in the database with both the existing items AND the new items...

So, if I have one Shoppingcart and two children and I now add 3 new items, I end up with 2 ShoppingCart entries in the ShoppingCart table and 7 ShoppingCartItem entries...

I traced the code and, the ShoppingCart entity is getting marked as Added as soon as a new ShoppingCartItem is added using AddObject()...

How can I prevent that?

Thanks a lot,

Stéphan

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

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

发布评论

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

评论(1

为人所爱 2024-09-18 14:23:17

最简单的解决方案是检索具有详细实体的现有 ShoppingCart,然后不执行任何 AddObject 调用。请改为调用 SaveChanges() 方法,这会将更改写入数据库,而无需创建新的 ShoppingCart 实体。

The simplest solution is to retreive the existing ShoppingCart with detail entities, and then not to perform any AddObject calls. Call the SaveChanges() method instead, this will write the changes to the database without creating a new ShoppingCart entity.

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