Getting Started
Architecture
NServiceBus
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Using the SQL Server transport with Entity Framework

NuGet Package: NServiceBus.Transport.SqlServer (8.x)
Target Version: NServiceBus 9.x

To avoid escalating transactions to the Distributed Transaction Coordinator (DTC), operations using Entity Framework must share their connection string with the SQL Server transport.

However, Entity Framework cannot directly use the connection string for the SQL Server transport when using the Database/Model First approach. In this case, Entity Framework requires a special connection string containing specific metadata.

The metadata can be added using EntityConnectionStringBuilder. The modified connection string can then be used to create an EntityConnection, which can then be used to create an instance of the generated DbContext type:

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
}

The DbContext generated Entity Framework does not have a constructor with an EntityConnection, but since it is a partial class, the constructor can be added:

partial class MySampleContainer
{
    public MySampleContainer(EntityConnection dbConnection)
        : base(dbConnection, true)
    {
    }
}