Multiple databases (multiple DbContexts) in one transaction using TransactionScope

2

I have got two DbContexts(One Model-first and the other one is code first) which connects to two different databases in MSSQL. Now when you call SaveChanges from any class, it writes data to both the databases at the same time using TransactionScope class. Code looks like below.

        using (TransactionScope scope = new TransactionScope())
        {
            using (Schema1Entities db1 = new Schema1Entities())
            {
                db1.SaveChanges();
            }
            using (Schema2Entities db2 = new Schema2Entities())
            {
                db2.SaveChanges();
            }
            scope.Complete();
        }

The problem raises during runtime. it is saying that

An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The underlying provider failed on Open.

Inner-exception message - {"The partner transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D025)"}

Turned on MSDTC, and no firewall is blocking the MSDTC. Need help immediately.

c#
sql-server
entity-framework
entity-framework-6
asked on Stack Overflow Jul 6, 2016 by zzzziiiirrrrkkkkkkkk • edited Jun 20, 2019 by Andrew

1 Answer

3

As per the comments under the question, this solved the issue:

using (TransactionScope scope = new TransactionScope())
{
    using (Schema1Entities db1 = new Schema1Entities())
    using (Schema2Entities db2 = new Schema2Entities())
    {
        db1.SaveChanges();
        db2.SaveChanges();
    }
    scope.Complete();
}
answered on Stack Overflow Jul 7, 2016 by Andrew

User contributions licensed under CC BY-SA 3.0