System.InvalidOperationException: An entity can only be attached as modified

孤者浪人 提交于 2019-12-25 05:23:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!