實體框架似乎實際上並未從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.
我在一個完全喪失。我已經建立了這樣幾百年的項目,從來沒有任何問題。由於它可能很重要,我運行最新的實體框架6.1.3。任何想法可能會發生在這裏?
你確定它是它正在查看的配置文件,可能你有多個配置文件? – pjobs
不是。項目根目錄中只有一個Web.config。 –
我假設你在Visual Studio中運行這個工具,確保你正在運行你的web項目作爲啓動項目來使用web.config。如果您正在運行另一個控制檯或.tests項目作爲啓動項,它將以配置文件形式提取它們的app.config文件 – pjobs