我想处理一个批量插入过程中的情况,其中可能存在具有相同主键的实体,这当然会导致SaveChanges抛出异常。分离一个实体并在另一次尝试上保存上下文
这是我有:(计数随着时间的foreach循环迭代次数下降)
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,实体确实去除
但它仍然在第二次尝试中抛出一个异常,喋喋不休地发出一声嘟PK。
我认为分离一个实体的原理是一样的,如果它从来没有在上下文中。我需要做其他事吗?
谢谢。
任何你不想检查对象是否存在之前的原因? –
究竟哪个对象? –
你可以检查实体是否存在于分贝之前添加?我认为它比添加更好,并且在catch中分离 –