【问题标题】:Can I specify the filename for a localdb database in entity framework 5?我可以在实体框架 5 中指定 localdb 数据库的文件名吗?
【发布时间】:2012-08-16 14:28:09
【问题描述】:

如果我将 Entity Framework 5 与 LocalDb 一起使用,有没有办法在 app.config/web.config 文件中指定数据库的文件名?

【问题讨论】:

    标签: .net entity-framework localdb


    【解决方案1】:

    经过进一步调查,它看起来确实很简单,但在阅读文档时并不清楚。

    首先你需要有实体框架部分的配置

      <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    

    一旦你有了它,你就需要指定你的连接字符串。默认情况下,连接字符串名称是您的上下文的完全限定名称。所以在我的测试应用程序中,上下文被称为“DataModel.Context”,所以我需要一个“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" />
    

    然后使用项目数据目录中的文件“database.mdf”。

    【讨论】:

    • 你应该把 放在哪个部分?
    • @WouterSchut 查看我的解释
    【解决方案2】:

    正如尼克所说,您需要提供&lt;entityFramework&gt; 标签的connectionString outside。所以App.config 的示例可能是这样的:

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

    还请注意,&lt;parameter value="mssqllocaldb" /&gt; 取决于您的 SQL Server 版本。 Check this answer for more information.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2023-03-25
      • 2015-10-26
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多