Entity Framework Caveats

Component: SQL Server Transport
NuGet Package NServiceBus.SqlServer (4-pre)
Target NServiceBus Version: 7.x
This page targets a pre-release version and is subject to change prior to the final release.

In order to avoid escalating transaction to DTC when using Entity Framework, the database connection has to be shared. However, sharing the connection string can be problematic when dealing with entities based on the Entity Framework ADO.Net Data Model (EDMX).

The DbContext generated by Entity Framework does not expose a way to inject a simple database connection string. The underlying problem is that Entity Framework requires an Entity Connection String that contains more information than a simple connection string.

However, it is possible to generate a custom EntityConnection and inject it into the Entity Framework DbContext instance, as shown here:

var entityBuilder = new EntityConnectionStringBuilder
    Provider = "System.Data.SqlClient",
    ProviderConnectionString = "the database connection string",
    Metadata = "res://*/MySample.csdl|res://*/MySample.ssdl|res://*/MySample.msl"

var entityConn = new EntityConnection(entityBuilder.ToString());

using (var mySampleContainer = new MySampleContainer(entityConn))
    // use the DbContext as required

In the snippet above the EntityConnectionStringBuilder class is used to create a valid Entity Connection String, which then enables a new EntityConnection instance to be created.

Keep in mind that although the DbContext generated by default by Entity Framework does not have a constructor that accepts an EntityConnection as a parameter, since it is a partial class, that parameter can be added using the following snippet:

partial class MySampleContainer
    public MySampleContainer(EntityConnection dbConnection)
        : base(dbConnection, true)
The snippet above assumes that the created entity data model is named MySample. The references should match the actual names used in the project.

Last modified