2

我一直在使用 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 用于 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);
};
4

1 回答 1

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();
于 2013-06-30T17:12:56.143 回答