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

坚强是说给别人听的谎言 提交于 2019-11-29 12:02:05

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11989371/can-i-specify-the-filename-for-a-localdb-database-in-entity-framework-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!