2

是否可以在没有 EntityKey 的情况下对从 ObjectContext 检索到的对象进行 MemberwiseClone?我正在使用带有 C# 的 Entity Framework 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();
    }
}

有人知道我的问题的简单解决方案吗?

4

1 回答 1

3

MemberwiseClone复制所有成员。如果您想避免复制任何成员,则必须进行自己的克隆。这是不可能的,这是有充分理由的。EntityKey唯一标识实体并且它是不可变的。设置后,您将无法更改它,因此您无法更改用于构建密钥的任何属性(在模型中标记为键的属性)。EntityKey也是引用类型,因此通过创建原始实体的成员明智克隆,您将引用相同的键实例。这样的实体将毫无用处。

于 2012-12-03T11:07:40.970 回答