簡體   English   中英

實體框架無法在Web.config中找到連接字符串

[英]Entity Framework Can't Find Connection String in Web.config

實體框架似乎實際上沒有從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。 有什么想法可能會在這里發生嗎?

我假設您在Visual Studio中運行此項,請確保您將Web項目作為啟動項目運行以使用web.config。 如果您正在運行另一個控制台或.tests項目作為啟動,它將獲取他們的app.config文件作為配置文件。

請記住,EntityFramework會在運行代碼的程序集的配置中搜索連接字符串。 例如,如果您使用單元測試運行器的測試方法執行EF方法,那么EF將在測試程序集中搜索它,而不是在存儲EF方法的位置搜索它。 我相信這可能是你的情況。

順便說一下 - 在EntityFramework 5中,當創建Edmx時它會自動生成DbContext,它使用name=ConnectionString ,而不僅僅是ConnectionString,所以我認為沒關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM