Monday, 20 April 2015

Entity Framework 6 connection string names

When you add Entity Framework to a .NET project, it adds the following to the app.config file:

<entityFramework>

  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="mssqllocaldb" />
    </parameters>
  </defaultConnectionFactory>
  <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
</entityFramework>

David shows that you can modify the defaultConnectionFactory section to use SQL Server with a connection string.

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">  
  <parameters>
    <parameter value="Data Source=.\sql2014;Initial Catalog=AdventureWorks2014;Integrated Security=True;" />
  </parameters>
</defaultConnectionFactory>

What might not be immediately obvious is that you can also refer to an existing connectionString by name. So if you already have:

<connectionStrings>
  <add name="AW" connectionString="Data Source=.\sql2014;Initial Catalog=AdventureWorks2014;Integrated Security=True;" providerName="System.Data.SqlClient"/>

</connectionStrings>

Then you can just configure it like this instead:

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="AW" />
  </parameters>
</defaultConnectionFactory>

1 comment:

Mario said...

Great tip about using an existing connectionString. I was looking for that. Thanks!