Can I specify the filename for a localdb database in entity framework 5?

Nick Randell picture Nick Randell · Aug 16, 2012 · Viewed 11.2k times · Source

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?

Answer

Nick Randell picture Nick Randell · Aug 21, 2012

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.