我使用实体框架和ASP。NET MVC 4构建应用程序

我的解决方案分为两个项目;

一个类库,其中包括我的数据模型(.edmx)文件和一些自定义接口 引用上面类库的“容器”MVC项目

我的问题是,当我试图使用'MyEntites' DbContext时,我得到以下错误:

中找不到名为“MyEntities”的连接字符串 应用程序配置文件。

我猜这个问题与连接字符串位于类库的app.config而不是MVC项目的事实有关。

有人有什么建议吗?


当前回答

如果你在解决方案中有多个项目,那么在你有真理App.config的地方开始安装项目。

其他回答

我也遇到过同样的问题。我错过了把连接字符串到启动项目,因为我正在从其他层执行数据访问操作。同样,如果你的启动项目中没有app.config,那么添加app.config文件,然后向该配置文件添加连接字符串。

确保你已经在启动项目的ROOT web.config中放置了连接字符串。

I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception... Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario. Yeah, these things happen to veteran developers as well :)

在根web中添加一个连接字符串。'container' MVC项目的配置文件引用类库如下:

 <connectionStrings>

  <add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />

  </connectionStrings>

如果你不想使用“MyEntities”作为连接名,那么按照你的愿望更改它,但在你的MyEntities DbContext类中做以下更改:

MyEntities: DbContext
 {
   public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
 }

这个错误的原因是,如果我们没有在DbContext的派生类中指定连接字符串或连接字符串的名称(在您的情况下是MyEntities),那么DbContext将自动在根web中搜索连接字符串。配置文件,其名称与派生类名称相同(在您的情况下,它是My Entities)。

当您在项目中使用图层并在DataLayer中定义或安装实体框架并尝试运行项目时,会发生此问题

因此,为了克服这个问题,从Edmx文件所在的层复制连接字符串,并将连接字符串粘贴到main web.config中。

在web中添加Connectoinstrnig。配置文件

<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too"  ></ConnectionStiring>