Connection String Name and Entity Framework

asp.net-mvc, entity-framework, sql-server

Solution

One question I have always had, but could never find a definitive answer to - does the name of my connection string have to match the name of my DbContext in order for EF to work correctly?

No. You can pass a connection string name into the base constructor for DbContext, i.e.

public class MyDbContext : DbContext
{
    public MyDbContext()
      : base("MyConnectionStringName")
    {

    }
}

There's also a constructor on `DbContext` that takes a `DbConnection` argument if you prefer to create the connection yourself.

Finally, you can provide your own implementation of `IDbConnectionFactory` and use it instead of the default `LocalDbConnectionFactory` one specified in the `app.config`. You change it in the config or you set it at runtime as follows:

`Database.DefaultConnectionFactory = new MyCustomConnectionFactory();`

Problem

So I have been using Entity Framework for some time (on v5 for my main project). One question I have always had, but could never find a definitive answer to - does the name of my connection string have to match the name of my DbContext in order for EF to work correctly? It appears so (and I have never done anything differently), but I would prefer not to have to provide a "magic string" in my Web.config in order for EF to work. It would be better, in my opinion, to keep DefaultConnection as the name and EF connects up some other way. Here is the references from my Web.config (some names changed): ``` <connectionStrings> <add name="MyContext" connectionString="Data Source=|DataDirectory|MyDatabase.sdf" providerName="System.Data.SqlServerCe.4.0" /> </connectionStrings> ``` ...and...farther down... ``` <entityFramework> <contexts> <context type="MyProject.Path.To.MyContext, MyProject.Path.To, Version=1.0.0.0, Culture=neutral"> <databaseInitializer type="MyProject.Path.To.MyInitializer, MyProject" /> </context> </contexts> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework> ``` Any insight would be appreciated.

Original source