回滚实体框架SaveChanges()



例如,我将每个状态的人员数据添加到数据库中(这不是我要做的,但模型是一样的(。我们有各州名单,每个州都有数百万人口。因此,最初在代码中,我保存状态以获取状态ID,然后使用该ID批量插入人员数据。

如果在添加人员数据时出现问题,比如说2000万记录抛出了一些异常,有没有办法恢复已经保存在PeoplesState表中的数据?

如有任何建议,不胜感激。。

List <Peoples> PeopleList = new List<Peoples>();
int peopleCounter = 0;
foreach (var stateVal in States)
{
using (var context = new StateEntities())
{
State st = new State();
st.ID = stateVal.ID;
st.Name = stateVal.Name;
context.State.Add(st);
context.SaveChanges(); 
if (stateVal.Peoples != null )
{
foreach (var _p in stateVal.Peoples)
{
Peoples _people = new Peoples();
_people.Name = _p.Name;
_people.Age = _P.Age;
_people.State_ID = stateVal.ID; // Getting state ID from State object as it already saved to DB
PeopleList.Add(_people)
peopleCounter++;
if (peopleCounter == 100000)
{
InsertPeople(PeopleList, context); // does bulk insert when PeopleList reaches 100k
PeopleList.Clear();
peopleCounter = 0;
} 
}
}
}
}
private static void InsertPeople(List<Peoples> PeopleList, StateEntities context)
{
context.Configuration.AutoDetectChangesEnabled = false;
context.Configuration.ValidateOnSaveEnabled = false;
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, new System.TimeSpan(0, 30, 0)))
{
context.BulkInsert(PeopleList, options => options.BatchTimeout = 0);
context.SaveChanges();
transactionScope.Complete();
}
}

您可以使用SQLtransaction进行回滚。它得到EF的支持。

using (var context = new SchoolContext())
{
using (DbContextTransaction transaction = context.Database.BeginTransaction())
{
try
{
//**TODO: Do your bulk insert codes here**

// Save changes data in context
context.SaveChanges();

// Commit changes
transaction.Commit();
}
catch (Exception ex)
{
// Rollback all changes
transaction.Rollback();
}
}
}

参考编号:https://learn.microsoft.com/en-us/ef/core/saving/transactions

最新更新