简体   繁体   中英

Using nested transactions in C# DataContext DNN

I am using this basic structure:

using(IDataContext ctx = DataContext.Instance())
{
  try{
    ctx.BeginTransaction();

    ctx.Commit();
  }
  catch(Exception)
  {
    ctx.RollbackTransaction();
    throw;
  }
}

What I would like to do is to nest transactions so that I can build using functional programming.

Very simplified version:

public void DoSomething(){
  using(IDataContext ctx = DataContext.Instance())
  {
    try{
      ctx.BeginTransaction();
       // make a change to the data
      ctx.Commit();
    }
    catch(Exception)
    {
      ctx.RollbackTransaction();
      throw;
    }
  }  
} 

public void CallingFunction(){
  using(IDataContext ctx = DataContext.Instance())
  {
    try{
      ctx.BeginTransaction();
      //do some stuff
      DoSomething();
      //do some other stuff
      ctx.Commit();
    }
    catch(Exception)
    {
      ctx.RollbackTransaction();
      throw;
    }
  }  
} 

So I want to be able to have multiple 'CallingFunctions' that all call DoSomething(), but if there is an exception thrown in the code that comes in CallingFunction after DoSomething, then I want DoSomething to roll back also.

DoSomething may be in the same class as CallingFunction or it may be in another class.

Surely this is possible, but I haven't been able to find the answer. Thank you for your assistance.

After checking my code, I realised that it is using DataContext from the DotNetNuke.Data namespace. Perhaps a DNN expert can assist?

You should inject the context in all the functions that need to use it, instead of having create their own. That way all changes before commit are on the same transaction and you can rollback everything if anything errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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