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

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

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

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

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

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

有人有什么建议吗?


当前回答

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

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

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

其他回答

确保你的项目(使用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...
}

你是对的,这是因为类库(其中.edmx文件)不是你的启动/主项目。

您需要将连接字符串复制到主项目配置文件。

如果你的启动/主项目没有配置文件(就像在我的控制台应用程序的情况下),只需添加一个(启动项目-添加新项->应用程序配置文件)。

更多相关信息可以在这里找到: MetadataException:无法加载指定的元数据资源

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

当我试图在AutoCAD插件中使用EF时,出现了这个错误。CAD插件从acad.exe.config文件中获取连接字符串。将上面提到的连接字符串添加到acad配置文件中,它就可以工作了。

功劳归于诺曼。来自adn网的袁。