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.
Connection strings used by the Entity Framework contain information used to connect to the underlying ADO.NET data provider that supports the Entity Framework. They also contain information about the required model and mapping files.
The original connection string is auto-generated by the Entity Data Model wizard. The connection string then cannot be changed - it remains disabled in the properties window of the . edmx designer.
Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With