0

我正在尝试更新名为“Hero”的表,正在使用DataContext,代码如下所示:-

//linq to sql table (automatic generated)
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Hero")]
    public partial class Hero : INotifyPropertyChanging, INotifyPropertyChanged
    {
          //fields methods etc..
    }

还有我自己的偏职英雄...

    public partial class Hero : IHero {
           //my fields and methods etc...

            public void Save() {
                using(GameDBDataContext db = new GameDBDataContext()) {
                    db.Heros.Attach(this, true);
                    db.SubmitChanges();
                }
        }
}

但它正在抛出这个:-

System.InvalidOperationException: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.

这个问题的解决方案是什么?

编辑:我试过这个: -

public void Save() {
    using(GameDBDataContext db = new GameDBDataContext()) {
        db.Heros.Attach(this, db.Heros.SingleOrDefault(x => x.id == EntityID));
    }
}

它抛出:-System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.

4

1 回答 1

0

我认为您没有Attach正确使用该方法。你看过这个http://msdn.microsoft.com/en-us/library/bb548978.aspx吗?

如果您传入的对象是在代码中创建的(而不是通过反序列化),它可能无法工作。如果它是通过反序列化制作的,那么我建议您尝试制作原始对象的副本,对其进行修改,并使用接受修改和未修改实体的重载Attach(Entity old, Entity new)

于 2012-11-02T23:21:42.920 回答