从EntityCollection复制到EntityCollection不可能吗? [英] Copying from EntityCollection to EntityCollection impossible?

查看:103
本文介绍了从EntityCollection复制到EntityCollection不可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何执行此操作(伪代码):product1.Orders.AddRange(product2.Orders);

How would you do this (pseudo code): product1.Orders.AddRange(product2.Orders);

但是,函数 AddRange不存在,那么如何将EntityCollection订单中的所有项目从product2复制到product1?

However, the function "AddRange" does not exist, so how would you copy all items in the EntityCollection "Orders" from product2 to product1?

应该很简单,但这不是...

Should be simple, but it is not...

推荐答案

问题比您想的要深。

您的 foreach 尝试失败,因为当您调用 product1.Orders.Add 时,该实体将从 product2.Orders ,从而使现有的枚举数无效,从而导致您看到异常。

Your foreach attempt fails, because when you call product1.Orders.Add, the entity gets removed from product2.Orders, thus rendering the existing enumerator invalid, which causes the exception you see.

那为什么从produc2中删除实体呢?好吧,这似乎很简单:因为订单一次只能属于一个产品。实体框架通过执行这样的规则来维护数据完整性。

So why does entity get removed from produc2? Well, seems quite simple: because Order can only belong to one product at a time. The Entity Framework takes care of data integrity by enforcing rules like this.

如果我理解正确,那么您的目的是实际上 复制 从一种产品到另一种产品的订单,对吗?

If I understand correctly, your aim here is to actually copy the orders from one product to another, am I correct?

如果是这样,则必须在<$内显式创建每个订单的副本。 c $ c> foreach 循环,然后将该副本添加到 product1

If so, then you have to explicitly create a copy of each order inside your foreach loop, and then add that copy to product1.

出于某种原因,这对于我来说还是很晦涩,因此没有自动的方法来创建实体的副本。因此,您几乎必须一一手动复制所有Order的属性。通过将此逻辑合并到Order类本身中,可以使代码看起来更整洁-创建一个名为Clone()的方法来复制所有属性。不过,请确保不要复制所有者产品参考属性,因为您的全部目的是给它另一个所有者产品,对吗?

For some reason that is rather obscure to me, there is no automated way to create a copy of an entity. Therefore, you pretty much have to manually copy all Order's properties, one by one. You can make the code look somewhat more neat by incorporating this logic into the Order class itself - create a method named Clone() that would copy all properties. Be sure, though, not to copy the "owner product reference" property, because your whole point is to give it another owner product, isn't it?

如果有不清楚的地方,不要犹豫,问更多的问题。祝你好运。

Anyway, do not hesitate to ask more questions if something is unclear. And good luck.


  • Fyodor

这篇关于从EntityCollection复制到EntityCollection不可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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