实体框架提供程序配置

3
我是使用EF 6.1 Code First。我正在运行时以编程方式配置连接字符串,如下所示:
myContext.Database.Connection.ConnectionString = "Data Source=(localdb)\v11.0;Initial Catalog=MyDb;Integrated Security=True;"

这可以正常工作,但只有在我的应用程序/ web.config中保留一些样板连接信息时才有效:
  <connectionStrings>
    <add name="MyDb" connectionString="Data Source=NOTUSED;Initial Catalog=NOTUSED;" providerName="System.Data.SqlClient" />
  </connectionStrings>

我怀疑这是因为我没有提供提供程序信息。我正在指定提供程序和defaultConnectionFactory部分(SQL Server / LocalDbConnectionFactory),但似乎并不在意:

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

如果我删除连接字符串部分,它会尝试附加到一个不存在的mdf文件:
System.Data.SqlClient.SqlException:无法将文件'C:\ My Project \ App_Data \ MyDb.mdf'附加为数据库MyDb。
通常,localdb连接字符串会导致路径为c:\ users \ my_user \ MyDb.mdf。因此,除非在.config文件中有连接字符串部分,否则似乎没有使用LocalDb工厂。
如何在每个上下文基础上指定EF从该连接字符串节点获取的providerName信息?还是我在这里搞错了?
1个回答

2

这可能与您构建连接的方式有关。如果您在DataContext上使用默认构造函数,则它将尝试从配置文件中查找连接字符串:

MyDbContext myContext = new MyDbContext() <- this uses the default constructor
myContext.Database.Connection.ConnectionString = "_conn_str_"

如果您在构造函数中传递连接字符串,则不需要使用配置文件条目:
using (MyDbContext myContext = new MyDbContext("_conn_str_")) {
   // the above line should not need an entry in the config file
}

希望这能帮到您。

这是正确的。我很抱歉之前没有确认。如果您愿意,我可以创建另一个悬赏问题并通过那种方式授予积分。 - RMD
嘿RMD,那太好了。很高兴它解决了你的问题。 - blorkfish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接