如何在没有TryUpdateModel()的情况下更新数据库

本文关键字:情况下 更新 数据库 TryUpdateModel | 更新日期: 2023-09-27 18:20:40

我一直在使用MVC4,只需调用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
    }
}

现在我正在为API使用NancyFX,并且我没有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);
};

如何在没有TryUpdateModel()的情况下更新数据库

基于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();