问题
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();
}
}
}
but it's throwing this :-
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?
EDIT: I have tried this :-
public void Save() {
using(GameDBDataContext db = new GameDBDataContext()) {
db.Heros.Attach(this, db.Heros.SingleOrDefault(x => x.id == EntityID));
}
}
and it throws :- 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.
回答1:
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 ?
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)
.
来源:https://stackoverflow.com/questions/13204076/system-invalidoperationexception-an-entity-can-only-be-attached-as-modified