Scott
Scott

Reputation: 153

C# Transaction Scope with 2 databases on same server causing exception

I have a scenario where I must insert data to 2 databases, but on the same database server and it must be inside a transaction. I am using entity framework 6 and I am wrapping each of my db saves inside a transaction scope. The issue is the first database save works fine but when I attempt the 2nd save to the other database an error occurs as follows.

Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I have read some articles that I must enable a feature within SQL server but I dont believe our DBA's will allow this modification. So I would like to verify first that there is no other solution in lieu of enabling DTC.

Here is my existing C# code, some specifics removed for brevity.

using (TransactionScope transaction = new TransactionScope())
{
    //database 1
    using (var context1 = new SomeContext())
    {
        //......
        //.....
        context1.SaveChanges();
    }

    //database 2
    using (var context2 = new SomeContext2())
    {
        //...
        context2.SaveChanges();
    }

    transaction.Complete();
}

Upvotes: 3

Views: 2105

Answers (1)

Xavier J
Xavier J

Reputation: 4726

Other than you writing a stored procedure to accomplish the work for you, there's no other way you're going to be able to get your code to do this without MSDTC. MSDTC does the job of brokering transactions across disparate sources (i.e. two databases).

Your DBAs may not allow you to make the change, because it's a server-level change, but they may turn on the feature themselves. Just note that if it's a development server, you'll eventually have to do the same to any other servers your project has to run on.

On MSDTC:

MSDTC is an acronym for Microsoft Distributed Transaction Coordinator. As the name says, MSDTC is a Windows service providing transaction infrastructure for distributed systems. In this case, a transaction means a general way of structuring the interactions between autonomous agents in a distributed system. Each transaction is a state transformation with four key properties – the ACID properties: Atomic (all or nothing), Consistent (legal), Isolated (independent of concurrent transactions) and Durable (once it happens, it cannot be abrogated). There are different techniques that implement the ACID properties but the most known one is two-phase commit.

Upvotes: 1

Related Questions