实体框架 4 使用查找引用保存实体克隆时出现问题
我有一个方法,我试图创建一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是因为序列化可以深度克隆整个对象图。当您只需要克隆顶级对象时,您不需要深度克隆。我通常通过在实体上实现 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 asDataMember
in case of data contract serialization).