Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I maintain IDocumentSession scope across more than one database in RavenDB?

Tags:

ravendb

My first thought is to consider some unit of work pattern, but what I'm doing is pretty small and lightweight and I want to avoid overengineering my solution..

I would like to have a single transaction scope across more than one RavenDB database.. something like

class WidgetFacade
{
    void SaveData (Widget widget, User user)
    {
          IDocumentStore documentStore = new DocumentStore { Url = "http://server:8080/" };

          IDocumentSession session  = documentStore.OpenSession("database1");
          session.Store(user);

          session = documentStore.OpenSession("database2");
          session.Store(widget);
          session.Savechanges();
          session.Dispose();
    }    
}
like image 576
Dave Avatar asked Nov 25 '25 12:11

Dave


1 Answers

You can't. Sessions are designed to operate on a single database.

However, you can get two sessions to participate in the same transaction.

var documentStore = new DocumentStore { Url = "http://server:8080/" };

using (var ts = new TransactionScope())
{
   using (var session = documentStore.OpenSession("database1"))
   {
      session.Store(user);
      session.SaveChanges();
   }

   using (var session = documentStore.OpenSession("database2"))
   {
      session.Store(widget);
      session.SaveChanges();
   }

   ts.Complete();
}

If the second operation fails for any reason, the first will also be rolled back - even though you've saved changes and completed the session.

like image 197
Matt Johnson-Pint Avatar answered Nov 28 '25 15:11

Matt Johnson-Pint