2013-06-30 31 views
2

我用MVC4所有的時間,我更新了我的實體數據庫只需調用TryUpdateModel();我如何不TryUpdateModel()

例(MVC4)

public ActionResult Edit(User user) 
{ 
    var userDb = _db.Users.Single(x => x.Id == user.Id); 

    if (TryUpdateModel(userDb)) 
    { 
     _db.SaveChanges(); // Done, database is updated 
    } 
} 

現在我使用的是更新數據庫NancyFX for API和我沒有TryUpdateModel()函數那裏。

Put["/"] = p => 
{ 
    var user = this.Bind<User>(); 
    var result = this.Validate(user); 

    if (!result.IsValid) 
    { 
     return Response.AsJson(result, HttpStatusCode.BadRequest); 
    } 

    // How to update my database here? No TryUpdateModel() function is avialable. 

    return Response.AsJson(user, HttpStatusCode.OK); 
}; 

回答

2

基於https://github.com/NancyFx/Nancy/wiki/Model-binding,我希望下面的工作:

// get a fresh copy of the user model for the purposes of getting the id (there may be a simpler way to do this) 
var rawUser = this.Bind<User>(); 
// read the user from the db 
var user = db.Users.Single(u => u.Id == rawUser.Id); 
// bind again, but using the db user as the target 
this.BindTo(user); 
// commit (I think EF may be smart enough not to do anything if BindTo() didn't actually change anything) 
db.SaveChanges(); 
+0

偉大的作品,感謝的人! – sed

相關問題