Connection string and entity structure

So, I have been using Entity Framework for some time (on v5 for my main project). One of the questions that I always had, but could not find a definitive answer to the question: should the name of my connection string match the name of my DbContext for EF to work correctly?

It seems like (and I never did anything else), but I would prefer not to provide a "magic line" in my Web.config so that EF can work. It would be better, in my opinion, to save DefaultConnection as a name, and EF is connected in some other way.

Here are the links 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 ... more ...

 <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.

+6
source share
1 answer

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

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

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

There is 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 standard LocalDbConnectionFactory specified in app.config . You change it in the configuration or set it at runtime as follows:

Database.DefaultConnectionFactory = new MyCustomConnectionFactory();

+11
source

All Articles