简体   繁体   English

升级到 ASP.NET Core 2.0 后无法创建迁移

[英]Unable to create migrations after upgrading to ASP.NET Core 2.0

After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.升级到 ASP.NET Core 2.0 后,我似乎无法再创建迁移了。

I'm getting我越来越

"An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Cannot open database "..." requested by the login. The login failed. Login failed for user '...'" “在类‘Program’上调用方法‘BuildWebHost’时发生错误。在没有应用程序服务提供商的情况下继续。错误:发生一个或多个错误。(无法打开数据库“...”登录请求。登录失败。登录用户'...'失败”

and

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time." “无法创建 'MyContext' 类型的对象。将 'IDesignTimeDbContextFactory' 的实现添加到项目中,或查看https://go.microsoft.com/fwlink/?linkid=851728了解设计时支持的其他模式。”

The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..\Web" (from the project/folder with the DBContext).我之前运行的命令是$ dotnet ef migrations add InitialCreate --startup-project "..\Web" (来自带有 DBContext 的项目/文件夹)。

Connection string: "Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"连接字符串: "Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"

This is my Program.cs这是我的 Program.cs

 public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();
}

You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.您可以在 Web 项目中添加一个实现 IDesignTimeDbContextFactory 的类。

Here is the sample code:这是示例代码:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
    public CodingBlastDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        return new CodingBlastDbContext(builder.Options);
    }
}

Then, navigate to your Database project and run the following from command line:然后,导航到您的数据库项目并从命令行运行以下命令:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource 资源

No need for IDesignTimeDbContextFactory .不需要IDesignTimeDbContextFactory

Run

add-migration initial -verbose

that will reveal the details under这将揭示下的细节

An error occurred while accessing the IWebHost on class 'Program'.访问“程序”类上的 IWebHost 时出错。 Continuing without the application service provider.在没有应用程序服务提供商的情况下继续。

warning, which is the root cause of the problem.警告,这是问题的根本原因。

In my case , problem was, having ApplicationRole : IdentityRole<int> and invoking services.AddIdentity<ApplicationUser, IdentityRole>() which was causing below error就我而言,问题是,有ApplicationRole : IdentityRole<int>并调用services.AddIdentity<ApplicationUser, IdentityRole>()导致以下错误

System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.

Solution 1: (Find the problem in 99% of cases)解决方案 1:(在 99% 的情况下找到问题)

Set Web Application project as Startup ProjectWeb 应用程序项目设置为启动项目

Run the following commands with -verbose option.使用-verbose选项运行以下命令。

Add-Migration Init -Verbose

-verbose option helps to actually uncover the real problem, It contains detailed errors. -verbose选项有助于真正发现真正的问题,它包含详细的错误。

Solution 2:解决方案2:

Rename BuildWebHost() to CreateWebHostBuilder() , because Entity Framework Core tools expect to find a CreateHostBuilder method that configures the host without running the app.BuildWebHost()重命名为CreateWebHostBuilder() ,因为Entity Framework Core tools期望找到一个CreateHostBuilder方法来配置主机而不运行应用程序。

.NET Core 2.2 .NET 核心 2.2

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
} 

.NET Core 3.1 .NET 核心 3.1

Rename BuildWebHost() to CreateHostBuilder()BuildWebHost()重命名为CreateHostBuilder()

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Solution 3:解决方案3:

Make sure you added Dbcontext to dependency injection: AddDbContext<TContext> will make both your DbContext type, TContext , and the corresponding DbContextOptions<TContext> available for injection from the service container.确保将Dbcontext添加到依赖注入: AddDbContext<TContext>将使您的 DbContext 类型TContext和相应的DbContextOptions<TContext>都可用于从服务容器注入。 This requires adding a constructor argument to your DbContext type that accepts DbContextOptions<TContext> .这需要向接受DbContextOptions<TContext>DbContext类型添加构造函数参数。

Example: In Startup.cs示例:在 Startup.cs 中

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));
}

AppDbContext code: AppDbContext代码:

public class AppDbContext: DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
      :base(options)
    { }

}
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
    }
}

Just rename BuildWebHost() to CreateWebHostBuilder() , because migrations use this method by default.只需将BuildWebHost()重命名为CreateWebHostBuilder() ,因为迁移默认使用此方法。

In my case, the cause of the problem was multiple startup projects.就我而言,问题的原因是多个启动项目。 I have three projects in my solution: Mvc, Api, and Dal.我的解决方案中有三个项目:Mvc、Api 和 Dal。 DbContext and Migrations in the Dal project. Dal 项目中的 DbContext 和迁移。

I had configured multiple startup projects.我已经配置了多个启动项目。 Both Mvc and Api projects were running when I clicked Start.当我单击开始时,Mvc 和 Api 项目都在运行。 But in this case I was getting this error.但在这种情况下,我收到了这个错误。

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time." “无法创建 'MyContext' 类型的对象。将 'IDesignTimeDbContextFactory' 的实现添加到项目中,或查看https://go.microsoft.com/fwlink/?linkid=851728了解设计时支持的其他模式。”

I could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.在将 Mvc 设置为唯一的启动项目并在 Package Manager Console 中选择 Dal 后,我可以成功添加迁移。

In the AppContext.cs besides AppContext class add another class:在 AppContext.cs 除了 AppContext 类添加另一个类:

// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();
          builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new AppContext(builder.Options);
    }
}

This will solve your second problem:这将解决您的第二个问题:

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, “无法创建“MyContext”类型的对象。将“IDesignTimeDbContextFactory”的实现添加到项目中,

After that you will be able to add-migration Initial and execute it by running update-database command.之后,您将能够添加迁移初始并通过运行update-database命令执行它。 However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error但是,如果在本地 SqlServer 中还没有数据库时运行这些命令,您将收到类似于第一个错误的警告:“错误

occurred while calling method 'BuildWebHost' on class 'Program'... The login failed.在类“程序”上调用方法“BuildWebHost”时发生...登录失败。 Login failed for user '...'"用户 '...' 登录失败"

But it is not error because migration will be created and it can be executed.但这不是错误,因为将创建迁移并且可以执行它。 So just ignore this error for the first time, and latter since Db will exist it won't happen again.所以第一次忽略这个错误,后面因为 Db 将存在它不会再次发生。

请确认您有参考

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />

You can try this solution from this discussion , which was inspired by this post .您可以从这个讨论中尝试这个解决方案,它受到这篇文章的启发。

public static IWebHost MigrateDatabase(this IWebHost webHost)
{
    using (var scope = webHost.Services.CreateScope())
    {
        var services = scope.ServiceProvider;

        try
        {
            var db = services.GetRequiredService<MyContext>();
            db.Database.Migrate();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while migrating the database.");
        }
    }

    return webHost;
}
public static void Main(string[] args)
{
    BuildWebHost(args)
        .MigrateDatabase()
        .Run();
}

Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/真正帮助我的是这篇文章: https ://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/

The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs.基本思想是,在从 .net core 1 到 2 的转换中,所有 db 初始化都应该从 StartUp.cs 移到 Program.cs 中。 Otherwise the EF tasks try and run your DB inits when doing tasks.否则,EF 任务会在执行任务时尝试运行您的数据库初始化。

"There is a nice section in the official migration docs ( https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade ) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn't what is causing your need to add an implementation of IdesignTimeDbContextFactory." “官方迁移文档 ( https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade ) 中有一个不错的部分,标题为“移动数据库初始化代码”,我似乎有错过了。因此,在您像我一样进入任何兔子洞之前,请确保这不是导致您需要添加 IdesignTimeDbContextFactory 实现的原因。”

From

https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation

When you create a new ASP.NET Core 2.0 application, this hook is included by default.当您创建新的 ASP.NET Core 2.0 应用程序时,默认情况下会包含此挂钩。 In previous versions of EF Core and ASP.NET Core, the tools try to invoke Startup.ConfigureServices directly in order to obtain the application's service provider, but this pattern no longer works correctly in ASP.NET Core 2.0 applications.在早期版本的 EF Core 和 ASP.NET Core 中,这些工具会尝试直接调用 Startup.ConfigureServices 以获取应用程序的服务提供者,但这种模式在 ASP.NET Core 2.0 应用程序中不再正常工作。 If you are upgrading an ASP.NET Core 1.x application to 2.0, you can modify your Program class to follow the new pattern.如果要将 ASP.NET Core 1.x 应用程序升级到 2.0,则可以修改 Program 类以遵循新模式。

Add Factory in .Net Core 2.x在 .Net Core 2.x 中添加工厂

public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
    {
        public BloggingContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

            return new BloggingContext(optionsBuilder.Options);
        }
    }

I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"我遇到了这个问题,通过 Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project" 解决了这个问题

Then run -> add-migration initial -verbose然后运行 ​​-> add-migration initial -verbose

in Package Manager Console在包管理器控制台中

Set as Startup Project设置为启动项目

If you want to avoid those IDesignTimeDbContextFactory thing: Just make sure that you don't use any Seed method in your startup.如果你想避免那些 IDesignTimeDbContextFactory 事情:只要确保你在启动时不使用任何 Seed 方法。 I was using a static seed method in my startup and it was causing this error for me.我在启动时使用了静态种子方法,这对我造成了这个错误。

I was facing the error我正面临错误

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time." “无法创建 'MyContext' 类型的对象。将 'IDesignTimeDbContextFactory' 的实现添加到项目中,或参阅https://go.microsoft.com/fwlink/?linkid=851728了解设计时支持的其他模式。”

This is how my problem was solved.我的问题就是这样解决的。 Run the below command while you are in your solution directory在解决方案目录中运行以下命令

 dotnet ef migrations add InitialMigration --project "Blog.Infrastructure" --startup-project "Blog.Appication"

Here Application is my startup project containing the Startup.cs class & Infrastructure is my project containing the DbContext class.这里的 Application 是我的包含 Startup.cs 类的启动项目,而 Infrastructure 是我的包含 DbContext 类的项目。

then run update using the same structure.然后使用相同的结构运行更新。

dotnet ef database update --project "Blog.Infrastructure" --startup-project "Blog.Application"

Previously, you configured the seed data in the Configure method in Startup.cs.之前,您在 Startup.cs 的 Configure 方法中配置了种子数据。 It is now recommended that you use the Configure method only to set up the request pipeline.现在建议您仅使用 Configure 方法来设置请求管道。 Application startup code belongs in the Main method.应用程序启动代码属于 Main 方法。

The refactored Main method.重构的 Main 方法。 Add the following references to the Program.cs:将以下引用添加到 Program.cs:

using Microsoft.Extensions.DependencyInjection;使用 Microsoft.Extensions.DependencyInjection;

using MyProject.MyDbContextFolder;使用 MyProject.MyDbContextFolder;

 public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<MyDbConext>(); DbInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); }

There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around.在 2.0 中,从 Startup.Configure 中的 ef 播种 db 存在问题……您仍然可以通过这项工作来解决。 Tested and worked fine测试和工作正常

https://garywoodfine.com/how-to-seed-your-ef-core-database/ https://garywoodfine.com/how-to-seed-your-ef-core-database/

In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.就我而言,我遇到了问题,因为我在Startup.cs文件上调用了一个名为SeedData.EnsurePopulated()的方法。

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePages();
        app.UseStaticFiles();
        app.UseSession();
        app.UseMvc(routes =>
        {
            //
        });

        SeedData.EnsurePopulated(app);
    }
}

The work of SeedData class is to add initial data to the database table. SeedData类的工作是将初始数据添加到数据库表中。 It's code is:它的代码是:

public static void EnsurePopulated(IApplicationBuilder app)
    {
        ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
        if (!context.Products.Any())
        {
            context.Products.AddRange(
            new Product
            {
                Name = "Kayak",
                Description = "A boat for one person",
                Category = "Watersports",
                Price = 275
            },
            ....
            );
            context.SaveChanges();
        }
    }

SOLUTION解决方案

Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.在进行迁移之前,只需在 Startup.cs 文件中注释掉 SeedData类的调用。

// SeedData.EnsurePopulated(app);

That solved my problem and hope your problem is also solved in the same way.这解决了我的问题,希望你的问题也能以同样的方式解决。

I ran into same problem.我遇到了同样的问题。 I have two projects in the solution.我在解决方案中有两个项目。 which哪个

  1. API API
  2. Services and repo, which hold context models保存上下文模型的服务和存储库

Initially, API project was set as Startup project.最初,API 项目被设置为启动项目。

I changed the Startup project to the one which holds context classes.我将Startup 项目更改为包含上下文类的项目。 if you are using Visual Studio you can set a project as Startup project by:如果您使用的是Visual Studio ,您可以通过以下方式将项目设置为启动项目:

open solution explorer >> right-click on context project >> select Set as Startup project打开解决方案资源管理器>>右键单击上下文项目>>选择设置为启动项目

First of all make sure you have configured your database in Startup.cs In my case, i was getting this error since i didn't specify the below in Startup.cs首先确保您已在Startup.cs中配置了数据库在我的情况下,我收到此错误,因为我没有在Startup.cs中指定以下内容

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsAssembly("<Your Project Assembly name where DBContext class resides>")));

Using ASP.NET Core 3.1 and EntityFrameWorkCore 3.1.0.使用 ASP.NET Core 3.1 和 EntityFrameWorkCore 3.1.0。 Overriding the OnConfiguring of the context class with a parameterless constructor only仅使用无参数构造函数覆盖上下文类的 OnConfiguring

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json")
           .Build();
        var connectionString = configuration.GetConnectionString("LibraryConnection");
        optionsBuilder.UseSqlServer(connectionString);
    }
}

I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet自从我提到旧的 Microsoft.EntityFrameworkCore.Tools.DotNet 以来,我遇到了同样的问题

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />

After upgrading to the newer version it got resolved升级到新版本后解决了

在主项目的 appsettings.json 文件中,我将“复制到输出目录”设置为“始终复制”并且它有效。

Sample DB context class for .net core console applications .net 核心控制台应用程序的示例数据库上下文类

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace EmailServerConsole.Data
{
    public class EmailDBContext : DbContext
    {
        public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options) { }
        public DbSet<EmailQueue> EmailsQueue { get; set; }
    }

    public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
    {
        EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<EmailDBContext>();
            var connectionString = configuration.GetConnectionString("connection_string");
            builder.UseSqlServer(connectionString);
            return new EmailDBContext(builder.Options);
        }
    }
}

You also can use in the startup class constructor to add json file (where the connection string lies) to the configuration.您还可以在启动类构造函数中使用将 json 文件(连接字符串所在的位置)添加到配置中。 Example:例子:

    IConfigurationRoot _config;
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        _config = builder.Build();
    }

For me it was because I changed the Output Type of my startup project from Console Application to Class Library .对我来说,这是因为我将启动项目的Output TypeConsole Application更改为Class Library

Reverting to Console Application did the trick.恢复到Console Application就可以了。

I had this issue in a solution that has:我在一个解决方案中遇到了这个问题:

  • a .NET Core 2.2 MVC project .NET Core 2.2 MVC 项目
  • a .NET Core 3.0 Blazor project .NET Core 3.0 Blazor 项目
  • The DB Context in a .NET Standard 2.0 class library project .NET Standard 2.0 类库项目中的数据库上下文

I get the "unable to create an object..." message when the Blazor project is set as the start up project, but not if the MVC project is set as the startup project.当 Blazor 项目设置为启动项目时,我收到“无法创建对象...”消息,但如果 MVC 项目设置为启动项目,则不会。

That puzzles me, because in the Package Manager Console (which is where I'm creating the migration) I have the Default project set to a the C# class library that actually contains the DB Context, and I'm also specifying the DB context in my call to add-migration add-migration MigrationName -context ContextName , so it seems strange that Visual Studio cares what startup project is currently set.这让我感到困惑,因为在包管理器控制台(我正在创建迁移的地方)中,我将默认项目设置为实际包含 DB 上下文的 C# 类库,并且我还指定了 DB 上下文我对 add-migration add-migration MigrationName -context ContextName ,所以 Visual Studio 关心当前设置的启动项目似乎很奇怪。

I'm guessing the reason is that when the Blazor project is the startup project the PMC is determining the version of .NET to be Core 3.0 from the startup project and then trying to use that to run the migrations on the .NET Standard 2.0 class library and hitting a conflict of some sort.我猜原因是当 Blazor 项目是启动项目时,PMC 正在确定启动项目中的 .NET 版本为 Core 3.0,然后尝试使用它在 .NET Standard 2.0 类上运行迁移图书馆并遇到某种冲突。

Whatever the cause, changing the startup project to the MVC project that targets Core 2.2, rather than the Blazor project, fixed the issue不管是什么原因,将启动项目更改为针对 Core 2.2 的 MVC 项目,而不是 Blazor 项目,解决了问题

For me the problem was that I was running the migration commands inside the wrong project.对我来说,问题是我在错误的项目中运行迁移命令。 Running the commands inside the project that contained the Startup.cs rather than the project that contained the DbContext allowed me to move past this particular problem.在包含 Startup.cs 的项目而不是包含 DbContext 的项目中运行命令使我能够解决这个特定问题。

In my case setting the StartUp project in init helps.在我的情况下,在 init 中设置 StartUp 项目会有所帮助。 You can do this by executing你可以通过执行来做到这一点

dotnet ef migrations add init -s ../StartUpProjectName

Manzur Alahi is right !曼祖尔阿拉希是对的 I'm trying to learn Rider by JetBrains and I had the same error when I was trying to use dotnet-ef migrations add ... in Cmd, PowerShell, etc. but when I used Visual Studio IDE I didn't have problem.我正在尝试通过 JetBrains 学习 Rider,当我尝试在 Cmd、PowerShell 等中使用dotnet-ef migrations add ...时遇到了同样的错误,但是当我使用 Visual Studio IDE 时,我没有遇到问题。

I fixed the error with:我用以下方法修复了错误:

dotnet ef migrations add InitialMigration --project "Domain.Entities" --startup-project "WebApi"

and this to update the database这是为了更新数据库

dotnet ef database update --project "Domain.Entities" --startup-project "WebApi"

just like Manzur Alahi said.就像 Manzur Alahi 说的那样。

如果上下文类在另一个类库项目中并且出现此错误,请将命令行默认项目更改为上下文项目并将解决方案启动项目设置为主API / ASP.net核心项目(您的DI容器在那里),然后重新-run 命令似乎 ef 核心工具包在https://github.com/dotnet/efcore/issues/23957https://github.com/dotnet/efcore/issues/23853中报告了此错误

I had same problem.我有同样的问题。 Just changed the ap.jason to application.jason and it fixed the issue只需将 ap.jason 更改为 application.jason 即可解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM