在程序集中找不到上下文类型

问题描述 投票:0回答:6

我正在使用 .NET 4.0、MVC3 和 EF5,代码优先。

我的解决方案分为三个项目,其依赖关系如下所示:

Project.Web -> Project.BLL -> Project.DAL

Project.DAL 层包含我的实体框架数据上下文类和所有实体,但我的启动项目是 Project.Web,因此它包含我的 Web.config、连接字符串和实际的 SQL 紧凑数据库。

我正在尝试启用迁移,以便可以向 EF 模型添加新表,而无需擦除现有数据。但是,当我运行“Enable-Migrations”时,我得到

No context type was found in the assembly 'Project.Web'.

如果我将启动项目设置为Project.DAL,错误将更改为

Could not load assembly 'Project.Web'. (If you are using Code First Migrations inside Visual Studio this can happen if the startUp project for your solution does not reference the project that contains your migrations. You can either change the startUp project for your solution or use the -StartUpProjectName parameter.)

有谁知道为什么会导致这个错误或者我可以做些什么来修复它?

asp.net entity-framework connection-string data-access-layer entity-framework-5
6个回答
82
投票

我最终在this问题中找到了答案。基本上,在包管理器控制台中有一个“默认项目”下拉列表。您需要将其设置为包含 EF 上下文的项目。


4
投票

我发现类似的帖子:在单独的程序集中启用上下文迁移?

示例:

enable-migrations -ContextProjectName MyProject.DBContexts -contexttypename MyProject.DBContexts.MyContextName -Verbose

1
投票

对于像我一样犯过这个错误的人:

你的上下文类必须继承自

DbContext
,就像这样:

public class DirectorRequestContext : DbContext
{
    public DbSet<DirectorRequest> DirectorRequests { get; set; }
}

1
投票

上面的其他答案都没有回答我的问题。

我最终放弃了包管理器控制台,因为它似乎使用 EF6 而不是 EFCore...

幸运的是,您可以从普通的 PowerShell 运行这些实体框架命令:

C:\MyRepository\MyProject dotnet ef migrations add InitialDbCreation

(确保您位于包含

DbContext
继承的项目目录中)。

最后,我得到了真正的错误:

Your startup project 'FantasyFitness' doesn't reference Microsoft.EntityFrameworkCore.Design. 
This package is required for the Entity Framework Core Tools to work. 
Ensure your startup project is correct, install the package, and try again.

因此,我转到项目上的“管理 NuGet 包”并安装

Microsoft.EntityFrameworkCore.Design
,关闭所有可能锁定文件的 IDE,然后它终于起作用了。

请注意,我什至不必运行

Enable-Migration
命令即可使其正常工作......这太神奇了。


0
投票

如果由于某种原因您的具有连接的类不在项目中,也会发生这种情况。因此,右键单击并“添加到项目”即可解决问题。


0
投票

我的问题是我同时安装了 EF6 和 EntityFrameworkCore,我必须通过在包管理器控制台中指定来解决此问题:

EntityFrameworkCore\Add-Migration
© www.soinside.com 2019 - 2024. All rights reserved.