我有一个ASP.NET MVC POST操作,用于在提交表单时保存实体。它适用于插入但不适用于更新,数据库不会被调用,因此它显然没有跟踪更改,因为它是“分离的”。我正在使用带有.NET 4的实体框架:
//POST: /Developers/Save/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
DataContext.DeveloperData.Insert(developer);
}
//save changes - TODO: doesn't update...
DataContext.SaveChanges();
//redirect to developer list.
return RedirectToAction("Index");
}
非常感谢任何想法,谢谢,
贾斯汀
答案 0 :(得分:1)
您永远不会将新数据应用于上下文。您可以使用Stub Entity技巧来避免查询。
尝试类似这样的事情(如果有错误,请从内存,sry):
public ActionResult Save(Developer developer)
{
developer.UpdateDate = DateTime.Now;
Developer d = new Developer { ID = developer.ID };
DataContext.Attach(d);
DataContext.ApplyCurrentValues(developer);
DataContext.SaveChanges();
}
答案 1 :(得分:1)
很抱歉发布到较旧的帖子但我遇到了这个问题,我发现的解决方案比我相信的效率更高一些。问题是当您将实体附加回上下文时,实体EntityState将重置为“Unchanged”。所以你必须把它恢复到“修改”状态。最简单的方法是将属性设置为自身。
//POST: /Developers/Save/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
DataContext.DeveloperData.Insert(developer);
}else{
DataContext.Attach(developer);
}
**developer.DeveloperID = developer.DeveloperID;
// Just ran into a problem that using the primary key like this doesn't reset the EntityState... but using string fields does change it so take that into consideration.
// OR IN YOUR CASE YOU CAN JUST MOVE DOWN THE UpdateDate set statement above like:
developer.UpdateDate = DateTime.Now;**
//save changes
DataContext.SaveChanges();
//redirect to developer list.
return RedirectToAction("Index");
}
这些更改中的任何一个都应该解决更新问题。
我仍在寻找的原因是这对我来说似乎是一种黑客攻击,并且必须采用“更清洁”的方式来实现它。我仍然觉得这是所提供解决方案中最便宜的。我有点震惊,设置一个属性自己触发了属性更改事件。我假设它会检查以确保值不相同。
答案 2 :(得分:0)
有关更新已分离对象的信息,请参阅here,但以下内容可以帮助您(作为if(developer.DeveloperID == 0)
的else块):
else
{
var original = DataContext.DeveloperData
.Where(d => d.DeveloperID == developer.DeveloperID)
.FirstOrDefault();
DataContext.DeveloperData.Attach(developer);
context.ApplyOriginalValues(original);
}
答案 3 :(得分:-1)
如果断开连接,则必须重新连接:
MSDN: Attaching and Detaching Objects (Entity Framework)
你可能想要:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
DataContext.Attach(developer);
}
//save changes - TODO: doesn't update...
DataContext.SaveChanges();
//redirect to developer list.
return RedirectToAction("Index");
}