我使用实体框架和ASP。NET MVC 4构建应用程序
我的解决方案分为两个项目;
一个类库,其中包括我的数据模型(.edmx)文件和一些自定义接口 引用上面类库的“容器”MVC项目
我的问题是,当我试图使用'MyEntites' DbContext时,我得到以下错误:
中找不到名为“MyEntities”的连接字符串 应用程序配置文件。
我猜这个问题与连接字符串位于类库的app.config而不是MVC项目的事实有关。
有人有什么建议吗?
我使用实体框架和ASP。NET MVC 4构建应用程序
我的解决方案分为两个项目;
一个类库,其中包括我的数据模型(.edmx)文件和一些自定义接口 引用上面类库的“容器”MVC项目
我的问题是,当我试图使用'MyEntites' DbContext时,我得到以下错误:
中找不到名为“MyEntities”的连接字符串 应用程序配置文件。
我猜这个问题与连接字符串位于类库的app.config而不是MVC项目的事实有关。
有人有什么建议吗?
当前回答
您的解决方案中是否使用了多个项目?
因为如果你是,你必须检查的web配置是与de .edmx文件在同一个项目中的配置
其他回答
如果您正在使用MVVM模型,请尝试将连接字符串复制到项目的所有部分。
例如,如果您的解决方案包含两个项目,类库项目和wpf项目,您必须复制后端项目(库类项目)的连接字符串,并将副本放在wpf项目的App.config文件中。
<connectionStrings>
<add name="DBEntities" ... />
</connectionStrings>
希望对你有帮助:)
这是因为您的上下文类是从DbContext继承的。我猜你的上司是这样的:
public MyEntities()
: base("name=MyEntities")
name =…应该改为你的connectionString的名字
我在运行MSTest时遇到了这个问题。如果没有“不隔离”的标志,我就无法让它工作。
希望这能帮助到一些人。花了我很多时间才弄明白。在IDE中一切都运行正常。在这个上下文中,实体框架有些奇怪。
确保你已经在启动项目的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 :)
你可以把连接字符串传递给EntityFramework,然后继续你的生活:
public partial class UtilityContext : DbContext
{
static UtilityContext()
{
Database.SetInitializer<UtilityContext>(null);
}
public UtilityContext()
: base("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True")
{
}
// DbSet, OnModelCreating, etc...
}