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

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

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

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

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

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

有人有什么建议吗?


当前回答

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>

其他回答

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

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

确保你的项目(使用DbContext)作为启动

OR

添加到app.config(或web.config)中设置为启动连接字符串的项目

OR

像这样调用命令

Update-Database -Script -ProjectName '<项目名称>' -StartupProjectName '<项目名称>' -ConnectionString '数据源=.;初始目录=<db名称>;集成安全性=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'

然后再试一次

你可以把连接字符串传递给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...
}

这是因为您的上下文类是从DbContext继承的。我猜你的上司是这样的:

public MyEntities()
    : base("name=MyEntities")

name =…应该改为你的connectionString的名字

正如您所猜测的,这与类库的app.config中的连接字符串有关。

将类app.config中的条目复制到容器的app.config或web中。配置文件