title: How can I wrap multiple business transactions under another transaction?
body: <p>In my project, a single service method is a business transaction. For instance, assume I have the following Service/Repository:</p>
  
  <pre><code>public interface IDocumentService {
  
      void CreateDocument(Document doc);
      void AttachFileToDocument(int documentId, string filepath);
  
  }
  
  public class DocumentService 
  {
      private readonly IDocumentRepository _repository;
  
      public DocumentService(IDocumentRepository repository)
      {
          _repository = repository;
      }
  
      public void CreateDocument(Document doc)
      {
          // do some validation
          // ..
  
          // create entity object....direct mapping, automapper, whatever
          DocEntity entity = new DocEntity()
          entity.Name = doc.Name;
          // etc
  
          using (var db = new DbEntities())
          {
              _repository.Insert(db, doc);
              _repository.AddSource(db, entity, doc.Sheet.SourceId);
  
              db.SaveChanges();
          }
      }
  
      public void AttachFileToDocument(int documentId, string filepath)
      {
          using (var context = new DbEntities())
          {
              DocEntity doc = _repository.GetById(context, id);
              // validation etc
  
              using (var tran = context.Database.BeginTransaction())
              {
                  try
                  {
                      // ..
                      // determine filename
                      // copy file
                      // update pointer to file in doc database
                      // ..
  
                      // save changes
                      context.SaveChanges();
  
                      tran.Commit();
                  }
                  catch (System.Exception)
                  {
                      tran.Rollback();
                      throw;
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>These are two separate things, so they get their own method. However, <strong>some times</strong> but not all, they would both be required and need to be atomic. I have tried to create a new service method that wraps these in a transaction, but it will not rollback the db create.</p>
  
  <p>How else can I achieve this using the same general design pattern - or is this not a good pattern to follow in this case - one context per business transaction?</p>