tags:

views:

28

answers:

1

I´m trying to update a db record using linq to sql

First i query for it

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.

A: 

Hey,

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).

Brian
Hey Thanks for the quick reply. I commented out the call to attach and it updated successfuly. But I been updating all my entities like this throughtout the project and its been working. Do you know why in this particular case it didnt? :D thx
Thiago
Not sure... entities that are already queried with a data context know about that data context; attach was meant for entities not attached to the context, so I thought it wasn't supposed to work that way.. so I'm puzzled that it did work for you that way... Unless do you turn off change tracking in your project, or something else that may be on in this case?
Brian