是否可以在没有EntityKey的情况下对从ObjectContext检索到的对象执行MemberwiseClone操作?我使用的是带有C#的实体框架4.1
如果我尝试更改Id,则会得到以下异常:
The property 'Id' is part of the object's key information and cannot be modified
如果我尝试将EntityKey设置为null:
The EntityKey property can only be set when the current value of the property is null.
我的代码:
Offer newOffer = offer.ShallowCopy();
// does not work...
newOffer.EntityKey = null;
/ does not work either...
newOffer.Id = Guid.NewGuid()
this._context.Add<Offer>(newOffer);
this._context.SaveChanges();..。
public partial class Offer
{
public Offer ShallowCopy()
{
return (Offer)this.MemberwiseClone();
}
}有没有人知道我的问题的简单解决方案?
发布于 2012-12-03 19:07:41
MemberwiseClone会复制所有成员。如果您希望避免复制任何成员,则必须进行自己的克隆。有一个很好的理由来解释为什么这是不可能的。EntityKey唯一标识实体,并且它是不可变的。EntityKey也是引用类型,因此通过创建原始实体的成员克隆,您可以引用相同的键实例。这样的实体将是无用的。
https://stackoverflow.com/questions/13672469
复制相似问题