开发者

Save changes to object not part of the current db context

开发者 https://www.devze.com 2023-04-06 02:17 出处:网络
I have a web service to get an object, such as public Blah GetBlah(int blahID) { var db = new BlahContext...

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()
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号