我正在尝试更新名为“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.
答案 0 :(得分:0)
我认为您没有正确使用Attach
方法。你看过这个http://msdn.microsoft.com/en-us/library/bb548978.aspx吗?
如果您传入的对象是在代码中创建的(而不是通过反序列化),那么它可能无法正常工作。如果它是通过反序列化生成的,那么我建议你尝试制作原始对象的副本,修改它,并使用接受修改和未修改的实体Attach(Entity old, Entity new)
的重载。