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

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

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

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

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

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

有人有什么建议吗?


当前回答

我通过没有将项目设置为启动来得到这一点,正如另一个答案所示。我对此的贡献-当做Add-Migrations和Update-Database时,在Nuget Package Manager Console中指定启动项目作为命令的一部分(不包括'['或']'字符,这只是为了告诉你你需要将位于那里的文本更改为你的项目名称):

Enable-Migrations Add-Migrations -StartupProject[包含数据上下文类的项目名称] Update-Database -StartupProject[与上面的项目名称相同]

这样就行了。

其他回答

如果将启动项目更改为没有连接字符串的项目,也会发生这种情况。

右击解决方案-单击属性 在“公共属性”下,选择启动项目 在右窗格中选择项目 有连接字符串(在大多数情况下,这将是MVC项目- 启动解决方案的项目)

这也可能导致在调用代码中没有引用足够的dll引用。一个小小的笨拙的hack可以挽救你的一天。

我遵循DB First方法,并在DAL类库项目中创建了EDMX文件,这是对BAL类库的引用,而BAL类库又由WCF服务引用。

由于我在BAL中得到这个错误,我尝试了上面提到的方法从DAL项目的App.config复制配置细节,但没有解决。最终,在一个朋友的建议下,我只是添加了一个虚拟的EDMX文件到WCF项目(与相关的DB Connectivity等),所以它导入了所有必要的东西,然后我只是删除了EDMX文件,它只是摆脱了一个干净的构建问题。

在web中添加Connectoinstrnig。配置文件

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

Add an App.Config file Set the project as startup project. Make sure you add the connection strings after entityFramework section: <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> <!-- your connection string goes here, after configSection --> </connectionString>

是的,这很愚蠢。使用连接构建器可以避免复制连接字符串。VB。Net代码(在生产中使用,但在这里略有修改,因此视为未经测试,乐意协助解决任何问题),其中我有一个serverName变量,一个databaseName变量,我将它们传递到一个方法,并让它为我生成连接:

    Dim EfBuilder As New System.Data.EntityClient.EntityConnectionStringBuilder("metadata=res://*/VMware.VmEf.csdl|res://*/VMware.VmEf.ssdl|res://*/VMware.VmEf.msl;provider=System.Data.SqlClient;provider connection string=""data source=none;initial catalog=none;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""")
   Dim SqlBuilder As New Data.SqlClient.SqlConnectionStringBuilder(EfBuilder.ProviderConnectionString)
                        SqlBuilder.DataSource = serverName
                        SqlBuilder.InitialCatalog = databaseName
                        EfBuilder.ProviderConnectionString = SqlBuilder.ConnectionString
                        Using vmCtx As New VmEfConn(EfBuilder.ConnectionString)