问题描述
我相对较新,但我还是有点尴尬,因为这真的应该很简单...所有我想要做的是更新数据库表中的现有行。我使用EF(5我相信)代码。
对于MVC 3,我使用这种方法(它的工作):
ReportCommon reportcommon = db.ReportCommon.Single(r => r.ReportCommonId == id);
reportcommon.IP = StaticUtilities.GetIPAddress();
db.ObjectStateManager.ChangeObjectState(reportcommon,EntityState.Modified);
db.SaveChanges();
我已经尝试了一些我发现的例子,尽管他们没有错误的数据库没有更新...
[HttpPost]
public ActionResult Edit(CitizenEntryViewModel citizenDetails)
{
ActiveCitizen activeCitizen = db.ActiveCitizen.SingleOrDefault(m => m.ID == citizenDetails.ActiveCitizen.ID);
if(activeCitizen!= null)
{
citizenDetails.ActiveCitizen.CitizenUpdatedRecordOn = DateTime.Now;
//我们不编辑的字段,但仍需要传回
citizenDetails.ActiveCitizen.PublicID = activeCitizen.PublicID;美元
$ b activeCitizen = citizenDetails.ActiveCitizen;
db.SaveChanges();
}
我已经设法解决使用,显示如何只保存新的值:
db.Entry(activeCitizen).CurrentValues .SetValues(citizenDetails.ActiveCitizen);
注意,我遇到了错误:ObjectStateManager中已经存在具有相同密钥的对象ObjectStateManager无法跟踪具有相同键的多个对象
帮助我克服了这个问题。
因此,最终的代码:
var currentCitizen = db.ActiveCitizen.Find(citizenDetails.ActiveCitizen.ID);
db.Entry(currentCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
db.SaveChanges();
I'm relatively new to this but I'm still a little embarrassed as this really should be simple...
All I'm trying to do is update an existing row in a database table. I'm using EF (5 I believe) code first.
For MVC 3 I used this approach (which worked):
ReportCommon reportcommon = db.ReportCommon.Single(r => r.ReportCommonId == id);
reportcommon.IP = StaticUtilities.GetIPAddress();
db.ObjectStateManager.ChangeObjectState(reportcommon, EntityState.Modified);
db.SaveChanges();
I've tried a few examples that I've found and although they don't error the database doesn't get updated...
[HttpPost]
public ActionResult Edit(CitizenEntryViewModel citizenDetails)
{
ActiveCitizen activeCitizen = db.ActiveCitizen.SingleOrDefault(m => m.ID == citizenDetails.ActiveCitizen.ID);
if (activeCitizen != null)
{
citizenDetails.ActiveCitizen.CitizenUpdatedRecordOn = DateTime.Now;
// Fields we don't edit but still need to pass back
citizenDetails.ActiveCitizen.PublicID = activeCitizen.PublicID;
citizenDetails.ActiveCitizen.IsKIN = activeCitizen.IsKIN;
activeCitizen = citizenDetails.ActiveCitizen;
db.SaveChanges();
}
I have managed to resolve this issue using the following code mentioned in this SO post which shows how to save only the new values:
db.Entry(activeCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
Note, I experienced the error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
This SO post helped me overcome that issue.
The final code was therefore:
var currentCitizen = db.ActiveCitizen.Find(citizenDetails.ActiveCitizen.ID);
db.Entry(currentCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
db.SaveChanges();
这篇关于MVC 4,EF 5 SaveChanges不更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!