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

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

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

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

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

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

有人有什么建议吗?


当前回答

定期迁移

有两个选项——这里每个人都建议的第一个选项是确保连接字符串在Web中。项目配置文件。当使用来自Azure应用程序设置的连接字符串时,这意味着要重写Web。配置值与Azure值。

Azure或自动迁移(编程式)

如果你以编程方式运行迁移,还有第二个选项可用,它允许你使用动态获得的连接字符串(或通过Azure应用程序设置)运行迁移,而不将其存储在Web.config中:

在设置配置的TargetDatabase时,使用DbConnectionInfo构造函数,它接受一个连接字符串和一个提供者名称,而不是只接受一个连接名称的构造函数。如果您的连接字符串没有提供商名称,并且您使用的是SQL Server / Azure SQL,则使用"System.Data.SqlClient"

其他回答

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>

我有这个问题时,我使用多个项目,启动项目与web。EntityFramework项目的config和app.config。

为了避免这个问题,你必须:

您需要连接字符串在开始*。配置文件。 您需要将EntityFramework DLL安装到引用中

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

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

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

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

尝试将连接字符串复制到MVC项目中的.config文件中。