Entity Framework caveats

Component: SQL Server Transport | Nuget: NServiceBus.SqlServer (Version: 2.x)
Target NServiceBus Version: 5.x

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.

It is possible to generate a custom a custom EntityConnection and inject it into the Entity Framework DbContext instance:

Edit
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. Having that a new EntityConnection instance can be created.

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:

Edit
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