C# 调用SaveChanges时,附加的实体不会使用新值进行更新
这个代码有什么问题吗?我的实体没有得到更新C# 调用SaveChanges时,附加的实体不会使用新值进行更新,c#,.net,entity-framework,C#,.net,Entity Framework,这个代码有什么问题吗?我的实体没有得到更新 public ActionResult UpdateNota(string notas) { if (Request.IsAjaxRequest()) { RegistroEntities registroEntities = new RegistroEntities(); Nota nota = JsonConvert.DeserializeObject<Nota>(notas);
public ActionResult UpdateNota(string notas)
{
if (Request.IsAjaxRequest())
{
RegistroEntities registroEntities = new RegistroEntities();
Nota nota = JsonConvert.DeserializeObject<Nota>(notas);
registroEntities.AttachTo("Notas",nota);
registroEntities.ApplyCurrentValues("Notas", nota);
registroEntities.SaveChanges(SaveOptions.DetectChangesBeforeSave);
return Json(new {success=true});
}
return View();
}
public ActionResult UpdateNota(字符串notas)
{
if(Request.IsAjaxRequest())
{
RegistroEntities RegistroEntities=新的RegistroEntities();
Nota Nota=JsonConvert.DeserializeObject(notas);
注册实体。附件(“Notas”,nota);
注册实体。应用当前值(“nota”,nota);
registroEntities.SaveChanges(SaveOptions.DetectChangesBeforeSave);
返回Json(新的{success=true});
}
返回视图();
}
查看,尤其是有关的部分
在本例中,您正在调用AttachTo
,这将实体置于未更改的状态
然后调用ApplyCurrentValues
,它将实体中的所有值复制到自己的值上;任何具有不同值的值都标记为已修改。(请注意,由于每个值只是复制到自身上,因此它们都没有不同的值,因此实体仍处于未更改的状态)
最后,调用SaveChanges
。由于实体处于未更改
状态,因此无需执行任何操作
本答案开头的MSDN文档链接包含有关正确方法的信息(请注意,添加实体使用的解决方案与更新实体不同)