2012-12-24 141 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