System.InvalidOperationException:只能以修改后的方式附加实体 [英] System.InvalidOperationException: An entity can only be attached as modified
问题描述
我正在尝试更新名为"Hero"的表,正在使用DataContext
,这是代码的样子:-
am trying to update table called "Hero" , am using DataContext
, here is how the codes looks like:-
//linq to sql table (automatic generated)
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Hero")]
public partial class Hero : INotifyPropertyChanging, INotifyPropertyChanged
{
//fields methods etc..
}
还有我自己的局部类英雄...
and there is my own partial class Hero ...
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.
该问题的解决方案是什么?
what is the solution for this problem?
我已经尝试过了:-
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.
推荐答案
我认为您没有正确使用Attach
方法.您是否看过 http://msdn.microsoft.com/en-us/library/bb548978.aspx 吗?
I don't think you're using the Attach
method correctly. Have you looked at this http://msdn.microsoft.com/en-us/library/bb548978.aspx ?
如果您要传递的对象是用代码创建的(而不是通过反序列化),则可能无法使用.如果它是通过反序列化完成的,那么我建议您尝试制作原始对象的副本,对其进行修改,并使用接受修改后的实体和未修改的实体Attach(Entity old, Entity new)
的重载.
If the object you're passing in was created in code (rather than through deserialization) it probably won't work. If it was made via deserialization then I would recommend you try making a copy of the original object, modifying it, and using the overload which accepts a modified and unmodified entity Attach(Entity old, Entity new)
.
这篇关于System.InvalidOperationException:只能以修改后的方式附加实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!