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

时间:2013-06-30 17:06:54

标签: c# entity-framework entity-framework-5 nancy

我一直在使用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
    }
}

现在我正在使用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);
};

1 个答案:

答案 0 :(得分: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();