【发布时间】:2013-10-25 15:00:10
【问题描述】:
我看到这个问题被问了很多,但是我还没有找到任何可以解决我遇到的问题的东西。
显然我正在使用实体框架来更新记录。但是,一旦更新完成,每当我尝试保存时,都会收到以下错误消息:
An object with the same key already exists in the objectstatemanager
起初,我从包含ZipCodeTerritory 模型对象zipToUpdate 的副本的视图中传递了一个集合对象。我通过拉出这个对象并只发送相关字段来更改代码。但是,我仍然遇到同样的错误。
奇怪的是我第一次运行这段代码时,它运行良好。之后的任何尝试都会出现错误。
控制器
这是调用编辑函数的方法中的代码
public static string DescriptionOnly(ZipCodeIndex updateZip)
{
if (!string.IsNullOrWhiteSpace(updateZip.newEffectiveDate) || !string.IsNullOrWhiteSpace(updateZip.newEndDate))
{
return "Neither effective or end date can be present if updating Territory Code only; ";
}
_updated = 0;
foreach (var zipCode in updateZip.displayForPaging.Where(x => x.Update))
{
ProcessAllChanges(zipCode, updateZip.newTerritory, updateZip.newStateCode, updateZip.newDescription, updateZip.newChannelCode);
}
_msg += _updated + " record(s) updated; ";
return _msg;
}
这是实际进行更新的方法。
private static void ProcessAllChanges(ZipCodeTerritory zipToUpdate, string newTerritory, string newStateCode, string newDescription, string newChannelCode)
{
try
{
if (!string.IsNullOrWhiteSpace(newTerritory)) zipToUpdate.IndDistrnId = newTerritory;
if (!string.IsNullOrWhiteSpace(newStateCode)) zipToUpdate.StateCode = newStateCode;
if (!string.IsNullOrWhiteSpace(newDescription)) zipToUpdate.DrmTerrDesc = newDescription;
if (!string.IsNullOrWhiteSpace(newChannelCode)) zipToUpdate.ChannelCode = newChannelCode;
if (zipToUpdate.EndDate == DateTime.MinValue) zipToUpdate.EndDate = DateTime.MaxValue;
_db.Entry(zipToUpdate).State = EntityState.Modified;
_db.SaveChanges();
_updated++;
}
catch (DbEntityValidationException dbEx)
{
_msg += "Error during update; ";
EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |EX| " + dbEx.Message);
}
catch (Exception ex)
{
_msg += "Error during update; ";
EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |MESSAGE| " + ex.Message);
}
}
编辑
ZipCodeIndex 对象包含ZipCodeTerritory 模型对象的列表。这些不是从 linq 查询中提取的,而是简单地从视图传递回控制器。这是启动进程的控制器方法的签名:
[HttpPost]
public ActionResult Update(ZipCodeIndex updateZip, string button)
【问题讨论】:
-
您能否添加实例化 _db 的代码,它是(我认为)您的上下文......以及处理的位?我试图弄清楚您是否保持打开对象上下文而不是正确处理但无法从您的代码中看到?我建议使用 using 语句包装以确保正确处理。
-
@BenjaminPaul:就是这样,谢谢。完全由我监督,但由于这是一个静态类,我实例化了
_db的一个实例,当一个方法被调用为属性并因此一遍又一遍地使用它时。如果你想回复帖子,我会接受。再次感谢! -
非常感谢...我已经添加了我的答案!很高兴我能帮上忙!
标签: c# .net asp.net-mvc-3 entity-framework