2

I need to keep two databases mirrored, but I can not do it with SQL Server mirroring. The project uses NHibernate 2.2 as ORM.

Is there any possible way to solve this problem? e.g: Any plugin/extension for NHibernate to save to multiple databases at the same time.

Sklivvz
  • 30,601
  • 24
  • 116
  • 172

1 Answers1

5

There are multiple similar questions on StackOverflow. Refer this, this and this.

You must be creating two SessionFactory and ISession instances, one for each database. Further, you should use TransactionScope and wrap your database actions against multiple databases in it.

Following code is copied from answer by "Ricardo Peres" for one of the questions above:

using (TransactionScope tx = new TransactionScope())
{
  using (ISession session1 = ...)
  using (ITransaction tx1 = session.BeginTransaction())
  {
    ...do work with session
    tx1.Commit();
  }

  using (ISession session2 = ...)
  using (ITransaction tx2 = session.BeginTransaction())
  {
    ...do work with session
    tx2.Commit();
  }

  tx.Complete();
}
Community
  • 1
  • 1
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
  • Thanks, but I was wondering if there is something that not implies change the code over all the application, something configurable perhaps. – mariaoialvarez Dec 22 '16 at 12:06
  • I really cannot say (in-fact no one can) how you will put this in your code. If you have any middle tier like Business Logic Layer, you can handle this at that level instead of changing entire application. If you are using single Repository for both the databases (because both databases share same structure), you can control this in Repository. – Amit Joshi Dec 22 '16 at 12:11