﻿# Using the SQL Server transport with Entity Framework


To avoid escalating transactions to the [Distributed Transaction Coordinator (DTC)](https://en.wikipedia.org/wiki/Microsoft_Distributed_Transaction_Coordinator), operations using [Entity Framework](https://learn.microsoft.com/en-us/ef/) 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](https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/connection-strings#databasemodel-first-with-connection-string-in-appconfigwebconfig-file) 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:

<!-- snippet: EntityConnectionCreationAndUsage -->

```cs
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
}
```

<!-- endsnippet -->

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:

<!-- snippet: DbContextPartialWithEntityConnection -->

```cs
partial class MySampleContainer
{
    public MySampleContainer(EntityConnection dbConnection)
        : base(dbConnection, true)
    {
    }
}
```

<!-- endsnippet -->

> [!NOTE]
> The code snippets above assume that the created entity data model is named `MySample`. The references should match the names used in the project.
