实体框架无法在Web.config中查找连接字符串

时间:2015-04-21 15:11:30

标签: c# entity-framework

实体框架似乎实际上没有从Web.config中读取连接字符串。

我开始了一个新项目并创建了一个上下文:

public class FooContext : DbContext
{
    public FooContext() :
        base("Foo")
    {
    }

    // DbSets here
}

然后,我为项目Web.config添加了一个连接字符串:

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <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="Foo" providerName="System.Data.SqlClient" connectionString="Data Source=Foo;Initial Catalog=Foo;Integrated Security=False;User Id=foo;Password=foo;MultipleActiveResultSets=True" />
  </connectionStrings>
  <appSettings>
      ...

我启用了迁移,生成了初始迁移,然后尝试更新数据库。一段时间后,更新失败,说它无法连接到数据库。所以我将我的项目DLL拉入LINQPad并运行以下内容:

var context = new FooContext();
context.Database.Connection.ConnectionString.Dump();

我得到以下输出:

Data Source=.\SQLEXPRESS;Initial Catalog=Foo;Integrated Security=True;MultipleActiveResultSets=True

它正在尝试连接到LocalDB,完全忽略了我的连接字符串。所以我尝试在上下文构造函数中更明确地使用"name=Foo"而不仅仅是"Foo"

public FooContext() :
    base("name=Foo")
{
}

为了它的价值,我以前从未这样做过。我甚至在同一个解决方案中有其他项目,我只是传递了连接字符串名称,并且它们一直工作正常。

我跳回到LINQPad并再次运行代码,现在我得到一个例外:

No connection string named 'Foo' could be found in the application config file.

我完全失去了。我已经设置了这样的项目100次,从来没有遇到任何问题。由于它可能很重要,我正在运行最新的Entity Framework,6.1.3。有什么想法可能会在这里发生吗?

2 个答案:

答案 0 :(得分:16)

我假设您在Visual Studio中运行此项,请确保您将Web项目作为启动项目运行以使用web.config。如果您正在运行另一个控制台或.tests项目作为启动,它将获取他们的app.config文件作为配置文件。

答案 1 :(得分:1)

请记住,EntityFramework会在运行代码的程序集的配置中搜索连接字符串。例如,如果您使用单元测试运行器的测试方法执行EF方法,那么EF将在测试程序集中搜索它,而不是在存储EF方法的位置搜索它。我相信可能是你的情况。

顺便说一句 - 在EntityFramework 5中,当创建Edmx时,它会自动生成DbContext,它使用name=ConnectionString,而不仅仅是ConnectionString,所以我认为没问题。