我希望通过每个动作运行增加1个名为BookViews
的int字段。
我的行动:
[HttpGet]
public IActionResult BookDetails(int id)
{
MultiModels model = new MultiModels();
model.UserListed = (from u in _userManager.Users orderby u.Id descending select u).Take(10).ToList();
using (var db = _iServiceProvider.GetRequiredService<ApplicationDbContext>())
{
var result = from b in db.books where (b.BookId == id) select b;
if (result.Count() != 0)
{
///error occure here
db.books.Update((from b in db.books where b.BookId == id select b.BookViews) + 1));
db.SaveChanges();
}
}
return View(model);
}
但是我的代码出错了。如何在每次运行中增加BookViews
字段1个单位并在数据库中更新?
尝试检索你想要的书,增加你的BookViews
,然后调用SaveChanges()
:
var currentBook = result.ToList().FirstOrDefault();
if(currentBook != null){
currentBook.BookViews++;
db.Books.Attach(currentBook );
//Changing the State
db.Entry(currentBook ).State = EntityState.Modified;
db.SaveChanges();
}
编辑
请尝试更具体,我们正在努力帮助您,但我无法猜测您所获得的错误或代码中的变量是什么,如果您不解释...