私は一括挿入プロセスで、同じ主キーを持つエンティティが存在する可能性がある状況を処理しようとしています。もちろん、これによりSaveChangesが例外をスローします。
ここに私が持っているものがあります:
try
{
_context.SaveChanges();
_context.Dispose();
_context = null;
_context = SelectContext<T>();
_commitCount = 0;
}
catch (System.Data.UpdateException updateEx)
{
//Remove from _context all the entries that errored in the SaveChange() process...
if (updateEx.StateEntries != null)
{
foreach (ObjectStateEntry stateEntry in updateEx.StateEntries)
{
if ((System.Data.EntityState)stateEntry.Entity.GetType().GetProperty("EntityState").GetValue(stateEntry.Entity, null) != System.Data.EntityState.Detached)
{
_context.Detach(stateEntry.Entity);
}
}
}
//Save context changes again this time without erroneous entries...
try
{
_context.SaveChanges();
_context.Dispose();
_context = null;
_context = SelectContext<T>();
_commitCount = 0;
}
catch (Exception ex)
{
//Welp, at the point, I'm clueless...
}
ObjectStateManager を見ると、エンティティは実際に削除されています (foreach ループが繰り返される回数だけカウントが減少します)。
しかし、2 回目の試行では依然として例外がスローされ、重複した PK について泣き言を言います。
エンティティを分離することは、そもそもコンテキストにない場合と同じだと思いました。他に何かする必要がありますか?
ありがとう。