Opening a DbContext connection within an existing SqlConnection

前端 未结 1 1426
名媛妹妹
名媛妹妹 2021-01-20 01:23

I\'m interested if opening an Entity Framework\'s DbContext connection within an existing ADO.NET SqlConnection should be discouraged, provided tha

相关标签:
1条回答
  • 2021-01-20 01:52

    The connection string is not the connection. You never pass the actual connection to the context, so it has to create a new one. As a consequence, the transaction will escalate to a distributed transaction in order to cover both connections.

    You need to pass the actual connection object to the context, using the appropriate constructor. In this case there will be only a single local transaction and no need to escalate it to a distributed transaction.

    In EF6+ you can simply pass the connection object. Change your method to this:

    void DoStuffWithEF(SqlConnection connection)
    {
        using(var context=new MyCodeFirstDbContext(connection,false)
        {
        // ...
        }
    }
    

    In previous versions you couldn't pass an open connection which required some unpleasant gymnastics, as described here

    0 讨论(0)
提交回复
热议问题