Save changes to object not part of the current db context
I have a web service to get an object, such as
public Blah GetBlah(int blahID) {
var db = new BlahContext...
}
and another web service
public UpdateBlah(int blahID) {
var db = new BlahContext...
var blah = GetBLah(blahID);
blah.someVariable = false;
... // how do I save this object?
}
But I don't think I can do SubmitChanges as the object was not created in the sa开发者_如何学运维me context.
When you call UpdateBlah
you need to pass the object as parameter so you can have the data to update.
Then you can choose two alternatives:
1. Mapping (manual or auto)
public UpdateBlah(object blahUpdated) {
var db = new BlahContext...
var blah = GetBLah(blahID);
// manually mapping
blah.someVariable = blahUpdated.someVariable;
// or using some kind to automapper (automapper.codeplex.com)
...
db.SubmitChanges()
}
2. Attach
You can attach
the object to the new datacontext
public UpdateBlah(object blahUpdated) {
var db = new BlahContext...
db.blahs.Attach(blahUpdated);
db.SubmitChanges()
}
精彩评论