How to run two Entity Framework Contexts inside TransactionScope without MSDTC?

前端 未结 3 979
無奈伤痛
無奈伤痛 2021-02-07 09:39

This problem is not readily reproducible in a simple example here but was wondering if anyone has any experience and tips, here is the issue:

  • using Entity
3条回答
  •  北海茫月
    2021-02-07 10:32

    I had a similar problem with SQL 2008, Entity Framework.

    I had two frameworks defined (EF1, and EF2) but using identical connection strings to a sql 2008 database.

    I got the MSDTC error above, when using nested "usings" across both. eg the code was like this:

    using (TransactionScope dbContext = new TransactionScope())
    {
         using (EF1 context = new EF1())
         {
             // do some EF1 db call
             using (EF2 context2 = new EF2())
             {
                  // do some EF2 db call
              }
          }
          dbContext.Complete();
    }
    

    It wasnt as simple as this, because it was split across several methods, but this was the basic structure of "usings".

    The fix was to only open one using at a time. No MTDSC error, No need to open distributed transactions on db.

    using (TransactionScope dbContext = new TransactionScope())
    {
         using (EF1 context = new EF1())
         {
             // do some EF1 db call
    
          }
         using (EF2 context2 = new EF2())
         {
                  // do some EF2 db call
         }
         dbContext.Complete();
    }
    

提交回复
热议问题