Skip to content

Transaction

so edited this page May 22, 2021 · 1 revision

事务支持

用法 1:

using(ITransientTransaction tran = dbContext.BeginTransaction())
{
    dbContext.Insert(entity);
    dbContext.Update(entity);
    dbContext.Delete(entity);
  
    /* 提交事务 */
    tran.Commit(); 
    /* 调用 ITransientTransaction.Dispose() 时,如果事务未提交,则会自动回滚 *
}

用法 2:

dbContext.UseTransaction(() =>
{
    dbContext.Insert(entity);
    dbContext.Update(entity);
    dbContext.Delete(entity);
});

用法 3:

dbContext.Session.BeginTransaction();
try
{
    /* do some things here */
    dbContext.Update(person);
    dbContext.Delete<Person>(a => a.Gender == null);

    dbContext.Session.CommitTransaction();
}
catch
{
    if (dbContext.Session.IsInTransaction)
        dbContext.Session.RollbackTransaction();
    throw;
}