无法使用ASP.net Core 2添加迁移

Dav*_*eau 3 c# ef-code-first asp.net-identity asp.net-core

我正在使用ASP.net Core 2和EntityFrameWorkCore 2.1.0构建一个新项目,我开始构建数据库结构.现在我必须进行第一次迁移以使我的数据库准备就绪,当我在Package Manager控制台中执行'Add-Migration Init'时,我收到此错误:

The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.
Run Code Online (Sandbox Code Playgroud)

我也尝试了这个文档https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations,我收到的消息是:

Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Run Code Online (Sandbox Code Playgroud)

我也跟着这篇文章没有任何成功.

如果我尝试没有Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0.2并使用简单的2表结构,我能够使它工作.

所以现在我需要你的帮助......

小智 15

确保安装了所需的NuGet包:

  1. Microsoft.EntityFrameworkCore.SqlServer
  2. Microsoft.EntityFrameworkCore.Design


Dav*_*eau 8

我找到了一些原因,为什么我们现在可以很难使用最新版本的ASP.net Core 2进行迁移.

首先,如果你只是从一个非ASP.net Core构建的旧项目迁移,你将不得不添加一个Context Factory来使迁移工作.在这里我自己的Context Factory:

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        builder.UseSqlServer("Server=(local)\\SQLEXPRESS;Database=yourdatabase;User ID=user;Password=password;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name));

        return new ApplicationDbContext(builder.Options);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果为了架构目的将项目划分为多个层,请在Repository Layer中或在DbContext所在的同一个库中添加Context Factory.

其次,在尝试添加迁移之前,必须在存储库库或DbContext所在的位置设置"设置为启动项目"的选择.然后,这些是您需要用于迁移的包:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer

就这样!

添加其他包时要小心,因为它们可能会破坏迁移系统.例如,如果您使用URF等工作单元和存储库框架并安装URF.Core.EF.Trackable -Version 1.0.0-rc2,您将无法再添加迁移.而是使用URF.Core.EF.Trackable -Version 1.0.0-rc1.我想这可能会发生在很多其他软件包上.

最后,阅读本文将会有所帮助.这有点过时,但它可以帮助那里的人.

干杯