I need your help very much. I'd like to update object created in another datacontext; Here is my code. Insert statement works well but I can't write code for update
var dataContext = new ReconNewDataContext();
if (Id == 0)
{
var item = this;
dataContext.RequestIO.InsertOnSubmit(item);
dataContext.SubmitChanges();
Id = item.Id;
}
else
{
var item = this;
//update object
}
I've read Linq2SQL: Update object not cre开发者_Python百科ated in datacontext
I've tried to use .Attach(this) .Attach(this,true) .Attach(this, oldObjectFromBase) but always I've an errors.
I know I can get object from database and manually transfer data from modified object, but there will be new fields. It means that I must always append these new fields in Save() method.
Is there any "beautiful" method to update object created in another datacontext?
Check out this article: http://omaralzabir.com/linq_to_sql__how_to_attach_object_to_a_different_data_context/
Also, in your example, for update, try doing:
var item = new ObjectBeingUpdated();
//copy over properties from old object to new object, make sure pk's match
//Attach this new object
Something similar worked for my coworker I believe.
UPDATE: Check this out for more info about attach: http://blogs.msdn.com/b/dinesh.kulkarni/archive/2007/10/08/attach-if-you-have-something-detached.aspx
You could use the following pattern:
- Fetch existing object from repository
- Use AutoMapper to copy properties
- Save your object back.
精彩评论