简体   繁体   English

保存更改失败后,删除实体框架中的待处理插入

[英]Remove Pending Inserts in Entity Framework after failed savechanges

I am doing a batch insert of about 50 or so records. 我正在批量插入约50条记录。 It adds all the records and trys to save them all at once. 它添加所有记录,并尝试一次保存所有记录。

foreach(var item in MyItemsToSave)
{
   context.MyItems.Add(item);
}
context.SaveChantes();

If this fails I want to add them one by one. 如果失败,我要一个接一个地添加它们。 I have some other logic to handle failures but I don't want to lose 49 valid records because one failed. 我还有其他逻辑可以处理失败,但是我不想丢失49条有效记录,因为一条失败了。 I tried the following code: 我尝试了以下代码:

foreach(var item in MyItemsToSave)
{
    context.MyItems.Add(item);
    try{
        context.SaveChanges();
    }
    catch(Exception e)
    {
      .......do something
    }
}

These two pieces of code both run in the same process. 这两段代码都在同一进程中运行。 The first section runs as best case scenario and then the second runs if the first portion of code fails. 第一部分以最佳情况运行,然后如果第一部分代码失败,则第二部分运行。 What I determined is that the items in the batch portion of the code is still waiting to be inserted. 我确定的是,代码批处理部分中的项目仍在等待插入。 So when I call the savechanges method it is still trying to save the bad record. 因此,当我调用savechanges方法时,它仍在尝试保存错误记录。

How can I remove the records that failed (or all of them and start over)? 如何删除失败的记录(或所有记录并重新开始)?

EDIT NOTE: Even with the second go around it will still fail because as soon as bad record gets in to the list it will try to insert it when your try the next iteration of the loop. 编辑说明:即使第二遍,它仍然会失败,因为一旦不良记录进入列表,当您尝试循环的下一次迭代时,它将尝试插入该列表。

Better you save the changes one by one. 最好您一一保存更改。

foreach(var item in MyItemsToSave)
{

    try{
        context.MyItems.Add(item);
        context.SaveChanges();
    }
    catch(Exception e)
    {
       while (item.<FKColl>.Count > 0)
       {
           context.Detach(item.<FKColl>.First());
       }
      context.Detach(item);
    }
}

If any failed, Use Detach to remove the item from context(NOT IN DATASOURCE). 如果有任何失败,请使用“ Detach ”从上下文中删除该项目(不在数据源中)。 Also you should remove the fk items before detaching the item 另外,应拆下之前删除FK项目item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM