gpt4 book ai didi

c# - Entity Framework 更新不更新数据库表

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:00 25 4
gpt4 key购买 nike

我有一些我认为适用于 Entity Framework 更新 sql server 表的代码。单步执行代码时我没有收到错误。

var newsToUpdate = db.tblTips.Find(id);
//if(TryUpdateModel(newsToUpdate, "",))
try
{
db.SaveChanges();
}
catch (RetryLimitExceededException)
{
ModelState.AddModelError("", "unable to save changes");
}
  1. 注意我有 if(TryUpdateModel(... 行我不记得我是否在数据库表中的记录 DID 更新时使用过它。
  2. 我可以看到模型具有正确的 id
  3. 数据库表未更新。

我能做些什么来弄清楚为什么在 C# visual studio 中它不更新记录?没有错误。

更新:

我的模型是 tblTips ,我方法上的签名是

public ActionResult AddNews(tblTips tips, int? groupid, int? id)

似乎更新页面不知道其他列并试图更新它试图将列更新为 null 的所有列,其中在 db 表中该列是“非空”

是否“可以”(是的,我知道我应该使用 View 模型)执行以下操作以从更新中排除列?

db.Entry(tips).State = EntityState.Modified;
db.Entry(tips).Property(x => x.createdby).IsModified = false;
db.SaveChanges();

我想我不应该相信我在 Stackoverflow 上阅读的所有内容,上面的失败

Attaching an entity of type 'BRM.Data.Models.tblTips' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

最佳答案

就目前而言,您的代码现在说“从数据库中取出这个东西,然后保存我刚刚所做的任何更改”,但它实际上并没有改变您从数据库中取出的东西。

当您注释掉对 TryUpdateModel() 的调用时,您的问题很可能出现,ASP.NET MVC 使用它根据传递到 HTTP 请求的参数对给定对象进行修改。

我强烈建议使用版本控制系统,以便更轻松地及时查看您在任何给定时间点所做的更改,并撤消错误更改的内容。

关于c# - Entity Framework 更新不更新数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212088/

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