当数据模型位于单独的程序集中时添加迁移时出错

Error adding migration when data models are in a separate assembly

我刚刚设置了新项目,Pegasus(我的主要 Web 应用程序)和 PegasusEntities(我的数据库对象)。

我的 Pegasus 启动代码包括以下内容。

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(
        builder.Configuration.GetConnectionString(connectionString),
        builder => builder.MigrationsAssembly("PegasusEntities"));
});

如果我在程序包管理器控制台中将 Pegasus 设置为我的默认项目并尝试添加迁移,我会收到错误消息。

PM> add-migration CreateDatabase
Multiple startup projects set.
Using project 'Pegasus' as the startup project.
Build started...
Build succeeded.
Your target project 'Pegasus' doesn't match your migrations assembly 'PegasusEntities'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Pegasus")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

我不明白这个问题。项目在哪些方面“不匹配”?为什么它要求我将迁移程序集设置为 Pegasus?我在另一个项目中做同样的事情并且一直工作正常。

有人可以解释为什么这不起作用吗?

更新

虽然我在另一个项目中做同样的事情并且工作正常,但我尝试将包管理器控制台中的默认项目设置为 PegasusEntities。当我这样做时,我得到一个完全不同的错误。

PM> add-migration CreateDatabase
Multiple startup projects set.
Using project 'PegasusEntities' as the startup project.
Build started...
Build succeeded.
It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '2.0.0' (x64) was not found.
  - The following frameworks were found:
      5.0.12 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      5.0.16 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      6.0.4 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.

The specified framework can be found at:
  - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0&arch=x64&rid=win10-x64

这对我来说毫无意义。所有项目都以 net6.0 为目标。为什么要查找 Microsoft.NETCore.App 的版本 2?当我打开建议的 link 时,我看到一个页面显示 此版本已达到生命周期结束,这意味着它不再受支持。我们建议移动到受支持的版本,例如 7.0 Runtime。.

我昨天才遇到同样的问题。

该错误消息非常具有误导性,如果不是完全错误的话。

解决方法是将您的调试启动项目设置为实例化 DbContext 的项目,同时使该项目与在包管理器控制台中选择的实体保持一致。