2012-12-24 215 views
1

,我發現了以下錯誤:無法獲得實體框架連接

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

我剛剛建立了我的第一次EF項目。這是一個MVC應用程序,我在MVC項目中添加了實體模型。我還添加了一個DataAccess類和一個使用NUnit運行測試的類。最後,我將添加一個將引用DataAccess類的服務類。因此,目前的代碼看起來像這樣(我只是想獲得一個測試工作,以證明EF正在做它的事):

  • 測試固定電話數據訪問類
  • 數據訪問類調用實體框架
  • 實體框架訪問本地數據庫

目前,我只是試圖從一個表中返回所有行/一列。請記住,所有這些文件都在一個項目中。我讀了很多,這個問題源於有多個項目,但這似乎並不適用於我的情況。我檢查了「main」web.config文件。連接字符串看起來沒問題。我將同一個配置節(即connectionStrings)複製到Debug特定的配置文件中,但這並沒有什麼區別。任何想法,爲什麼我看到這個錯誤?

感謝, 周杰倫

Snapshot of the solution tree

連接字符串:

這是從對話框中的連接字符串創建實體訪問文件時(數據來源是兩個字符串中的一段[即本地主機]):

metadata=res:///EntityDataModel.csdl|res:///EntityDataModel.ssdl|res://*/EntityDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=URIntake;Integrated Security=True"

這是來自web.config文件的連接字符串。他們似乎是相同的,所有的實際目的:

metadata=res:///EntityDataModel.csdl|res:///EntityDataModel.ssdl|res://*/EntityDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=URIntake;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"

回答

1

微軟茲拉特科·Michailov說,

app.config is not in the binary directory where the exe is. Please do the following:

  1. Visually verify that the app.config with the expected content is in the directory where the exe is compiled. (Existence in the project root directory is not enough.)

  2. Use System.Configuration.ConfigurationManager from within your app to examine the content of the app.config your exe is using.

I’m also looking at the content of the connection string, and I can say that it may not work in a multi project environment (unless you’ve duplicated the EDM in each project).

The reason for that is 「.」 resolves to the directory where the exe is loaded from. If you want to reuse the same EDM, you at least have to make a few steps back in the path and then navigate to the project where the EDM is, e.g. 「......\Proj1\AdventureWorksModel」.

Additionally you may consider using the |DataDirectory| macro - when you load an AppDomain you can set |DataDirectory| to point to the exact directory where the EDM is, and then use that in the connection string, e.g. 「|DataDirectory|\AdventureWorksModel」.

If you are working on an ASP.NET project, you can use 「~」 which refers to the project root. In that latter case, you can’t reference a model outside your project’s hierarchy though.

欲瞭解更多信息Check Here

更新1:

在這裏你可以嘗試下面提到的步驟

  1. 清除的web.config文件連接字符串內容像下面

    enter image description here

  2. 然後從你的項目中刪除您*的.edmx文件

  3. 再次像下面一樣重新創建(樣本一)。不要忘了勾選 「在web.config中爲拯救實體conncetion設置:」

enter image description here

最後一步:之後去到web.config文件和檢查您的連接字符串是否與上述「實體連接字符串:」顯示的完全相同,如上顯示的那樣(我在上圖中的紅色標記上顯示它)。

我希望這對你有幫助。

+0

MVC應用程序是否有app.config文件?我在哪裏找到它?我編譯了應用程序,然後進行了搜索,但沒有看到app.config文件。 – birdus

+0

@birdus你可以把你的項目樹上的小圖像放在你的帖子上面嗎? – Sampath

+0

@birdus查看我的更新1部分了解更多詳情 – Sampath