在 .net core 2 class 库中迁移身份

Migrating Identity in .net core 2 class library

我一直在尝试将具有标识的 class 库添加到 .net core 2 项目中。

项目 Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<MyDbContext, IdentityRole>()
            .AddEntityFrameworkStores<MyDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
   }

Class图书馆:

namespace MSContext
{
    public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {
        public MyDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<MyDbContext>();
            builder.UseSqlServer(connectionString);
            return new MyDbContext(builder.Options);
        }
    }

    public class MyDbContext: IdentityDbContext<ApplicationUser>
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connectionString);
        }




        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
}

Class图书馆ApplicationUser.cs:

public class ApplicationUser : IdentityUser
{

}

当我尝试迁移时使用:Add-Migration

我收到这个错误:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: AddEntityFrameworkStores can only be called with a user that derives from IdentityUser.

当我搜索此错误时,我不断收到有关自定义身份模型的问题,但这不是我的情况。我只是想按原样迁移它。我错过了什么?

找到问题了。我用错了AddIdentity<>。 应该使用 ApplicationUser 而不是 MyDbContext。 这是更正后的版本:

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<MyDbContext>()
        .AddDefaultTokenProviders();