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

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

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

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

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

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

有人有什么建议吗?


当前回答

由包含.edmx文件的项目生成的连接字符串生成连接字符串,这似乎是app.config类型文件的保留,这些文件被复制到输出目录,并被可执行文件引用以存储运行时配置信息。

这在web项目中中断,因为没有自动的过程将随机的.config信息添加到web中。web项目的配置文件。

最简单的方法是将连接字符串从配置文件复制到web的连接部分。配置文件,忽略配置文件内容。

其他回答

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

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

是的,这很愚蠢。使用连接构建器可以避免复制连接字符串。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)

确保你已经在启动项目的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 :)

我在运行MSTest时遇到了这个问题。如果没有“不隔离”的标志,我就无法让它工作。

希望这能帮助到一些人。花了我很多时间才弄明白。在IDE中一切都运行正常。在这个上下文中,实体框架有些奇怪。

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>