gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:56 28 4
gpt4 key购买 nike

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

最佳答案

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

关于c# - 如何在没有 TryUpdateModel() 的情况下更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392789/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com