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

Chr*_*att 11 c# entity-framework

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

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

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

    // DbSets here
}
Run Code Online (Sandbox Code Playgroud)

然后,我向项目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>
      ...
Run Code Online (Sandbox Code Playgroud)

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

var context = new FooContext();
context.Database.Connection.ConnectionString.Dump();
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

Data Source=.\SQLEXPRESS;Initial Catalog=Foo;Integrated Security=True;MultipleActiveResultSets=True
Run Code Online (Sandbox Code Playgroud)

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

public FooContext() :
    base("name=Foo")
{
}
Run Code Online (Sandbox Code Playgroud)

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

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

No connection string named 'Foo' could be found in the application config file.
Run Code Online (Sandbox Code Playgroud)

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

pjo*_*obs 16

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