この質問は多く寄せられているようですが、私が抱えている問題を解決するものはまだ見つかりません。
明らかに、エンティティ フレームワークを使用してレコードの更新を実行しています。ただし、更新が完了すると、保存しようとするたびに次のエラー メッセージが表示されます。
An object with the same key already exists in the objectstatemanager
ZipCodeTerritory
最初は、モデル オブジェクトのコピーを含むビューからコレクション オブジェクトを渡していましたzipToUpdate
。このオブジェクトを引き出して、代わりに関連するフィールドを送信するだけで、コードを変更しました。ただし、まだ同じエラーが発生します。
また奇妙なのは、このコードを初めて実行したとき、正常に動作することです。その後の試みは、エラーが発生します。
コントローラ
edit 関数を呼び出すメソッドのコードは次のとおりです。
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)