实体框架 4 使用查找引用保存实体克隆时出现问题

发布于 2024-10-30 02:28:30 字数 498 浏览 0 评论 0原文

我有一个方法,我试图创建一个 Address 对象的副本。地址有一个指向 StateProvince 的外键引用。

// ... get address from context
var newAddress = Util.DataContractSerialization<Address>(sourceAddress); // serializes and deserializes into/from memory
newAddress.AddressId = Guid.Empty;
ctx.Attach(newAddress); // error!

我应该怎么做?这个错误的原因是因为当我调用 Attach 时 StateProvince 属性已经在上下文中,它尝试附加整个对象图。我当前的解决方法是一个辅助方法,它显式复制 StateProvinceId 但不复制 StateProvince 对象。

我想这个错误可能会发生在其他情况下,所以我想找出解决这个问题的正确方法。

I have a method where I am trying to create a duplicate of an Address object. Address has a foreign key reference to StateProvince.

// ... get address from context
var newAddress = Util.DataContractSerialization<Address>(sourceAddress); // serializes and deserializes into/from memory
newAddress.AddressId = Guid.Empty;
ctx.Attach(newAddress); // error!

How should I be doing this? The reason this errors is because the StateProvince property is already in the context when I call Attach, which tries to Attach the entire object graph. My current workaround is a helper method that explicitly copies the StateProvinceId but not the StateProvince object.

I would imagine this error could occur in other situations, so I want to figure out the right way to solve this problem.

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

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

发布评论

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

评论(1

凌乱心跳 2024-11-06 02:28:30

是的,这是因为序列化可以深度克隆整个对象图。当您只需要克隆顶级对象时,您不需要深度克隆。我通常通过在实体上实现 ICloneable 并手动克隆没有其关系的实体来实现此目的。除了手动将所有导航属性标记为不可序列化(IgnoreDataMemberAttribute 或在数据协定序列化的情况下不标记为 DataMember)之外,没有更好的方法了。

Yes that is because serialization makes deep clone of the whole object graph. You don't want deep clone when you need to clone only top level object. I'm usually doing this by implementing ICloneable on entities and clonning manually just entity without its relations. There is no better way except manullay marking all navigation properties as not serializable (IgnoreDataMemberAttribute or not marking as DataMember in case of data contract serialization).

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