2

I am using dapper with repository pattern. Below is the code for single repository insert. I need to call 2 or more repositories in service layer with transaction (in savecustomer method). How to apply transaction for the following method?

Protected void Execute(Action<IDbConnection> query) {
      using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            query.Invoke(db);
        }
    }

And my simplified call site:

public void SaveCustomer(CustomerDTO custDTO)
{
    Execute(db => db.Execute(saveCustSp, custDTO, CommandType.StoredProcedure));
}
Ajt
  • 1,719
  • 1
  • 20
  • 42

1 Answers1

2

If you want to extend your transaction outside the repositories, please consider using UnitOfWork. The detailed code could be found here: https://stackoverflow.com/a/45029588/5779732

With this code, you can span transaction across multiple repositories like below:

using(DalSession dalSession = new DalSession())
{
    UnitOfWork unitOfWork = dalSession.UnitOfWork;
    unitOfWork.Begin();
    try
    {
        //Your database code here
        repository1.DoThis();
        repository2.DoThat();

        unitOfWork.Commit();
    }
    catch
    {
        unitOfWork.Rollback();
        throw;
    }
}

You can also get sample code for generic repository with Dapper here: https://stackoverflow.com/a/45460483/5779732

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
  • is it possible to do myrepository class be a generic class because you are using a sealed class for repository...if it possible what needs to be changed? Pls let me know – Ajt Jul 08 '17 at 02:25
  • 1
    The code in linked answer is just for an idea. It may change as per your need. So, yes it may be generic in case you want to implement it that way. The only thing that matters is that, repository should accept UoW as DI. Other implementation details are upto you. – Amit Joshi Jul 08 '17 at 05:35