Updating an Entity with LINQ TO SQL
I´m trying to update a db record using linq to sql
First i query for i开发者_StackOverflowt
MyObject obj = (from o in objRepository.List where(o.ID == id) select i).SingleOrDefault();
then I try to update and modify the data
obj.Name = "some value"
dataContext.Attach(obj)
dataContext.Context.Refresh(RefreshMode.KeepCurrentValues, obj);
I'm getting an InvalidOperationException
on the line where the content is attached.
It says that its impossible to attach an Entity that already exists.
Can anyone please help me? Thank you.
Any object updated with LINQ to SQL is automatically known, so if you get the object from the repository, and it knows about the data context, you don't need to attach it. You can simply submitchanges() with the data context and those changes get updated to the database.
So when you query from the data context, as soon as a property changes its value, the data context already knows about the change, and a call to SubmitChanges() pushes it to the DB and updates that object's references (so you can drill through).
精彩评论