Question

I have a situation in which I have 2 databases.

Manager has Companies Table, based on this value I have to create a new DB.

So I am using TransactionScope. I want to know is the following correct?

Will this roll back both changes? In both DB's if error occurs?

using (TransactionScope ts = new TransactionScope())
{
    try
    {
        using(var ManagerContext = new ManagerEntities(
            ConnectionStringManager.GetManagerConnectionString()))
        {
            //Operations on Manager DB                         
            // Create new Company and get NEWCOMPANYID 
            // -- Used to create new DB
        }

        using(var companyContext = new CompanyEntities(
            ConnectionStringManager.GetCompanyConnectionString(
                NEWCOMPANYID.ToString())))
        {
            //Create New Company DB
        }

        ts.Complete();
    }
    catch (Exception ex)
    {
        ts.Dispose();
    }
}
Was it helpful?

Solution

As long as both those database contexts are TransactionScope aware, and don't explicitly have ambient transaction enlisting disabled (in the connection string, for example), then yes: that should work fine. If we assume that the two connection strings are different, this will definitely require a distributed transaction (DTC), though - whether that is OK is up to you. If the connection strings are identical, you might get away with the LTM instead (less overhead / configuration).

Note that as per the comments - you don't need the try/finally.

OTHER TIPS

This is OK, although it will trigger DTC as explained by Marc. You can avoid DTC by using a single SqlConnection (or EntityConnection) that both contexts share. You can switch the current database of a connection with ChangeDatabase. This avoids the need for distributed transactions.

You also need to open the connection explicitly because EF by default opens and closed it for every action. That causes multiple DTC enlistments (more than 2). This is a design flaw in EF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top