Reputation: 18295
If I'm using Entity Framework 5 with LocalDb, is there a way of specifying the filename of the database in the app.config/web.config file?
Upvotes: 14
Views: 12106
Reputation: 7457
As Nick mentioned, you need to provide the connectionString
outside of <entityFramework>
tags. So a sample App.config
could be like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="CSOMLocalDataProvider.CSOMContext"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\path\to\Database.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<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>
</configuration>
also note that <parameter value="mssqllocaldb" />
depends on the version of your SQL Server. Check this answer for more information.
Upvotes: 3
Reputation: 18295
On further investigation it looks like it is really simple, but isn't clear when reading the docs.
First of all you need to have the entity framework part of the configuration
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
Once you have that, you then need to specify your connection string. By default the connection string name is the fully qualified name of your context. So in my test app, the context was called 'DataModel.Context', so I need a connection string for 'DataModel.Context'
<connectionStrings>
<add name="DataModel.Context" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=database;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\database.mdf" providerName="System.Data.SqlClient" />
This then uses the file 'database.mdf' in the data directory of the project.
Upvotes: 19