【问题标题】:Error while migration - There is already an object named 'AspNetRoles' in the database. (Entity Framework Core)迁移时出错 - 数据库中已有一个名为“AspNetRoles”的对象。 (实体框架核心)
【发布时间】:2018-08-22 04:58:13
【问题描述】:

我正在尝试使用 ASP.NET Identity Core 添加自定义配置文件详细信息。我已尝试将IdentityUser 类扩展如下:

public class ApplicationUser : IdentityUser
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
}

这是我继承 IdentityDbContext 的 ApplicationDbContext:

public class ApplicationIdentityDbContext : IdentityDbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=TokenDatabase;Trusted_Connection=True;");
    }
}

这是我的startup.cs 文件:

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // ===== Add our DbContext ========
            services.AddDbContext<ApplicationIdentityDbContext>();

            // ===== Add Identity ========
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationIdentityDbContext>()
                .AddDefaultTokenProviders();



            // ===== Add Jwt Authentication ========
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims

            services
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = Configuration["JwtIssuer"],
                        ValidAudience = Configuration["JwtIssuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                        ClockSkew = TimeSpan.Zero // remove delay of token when expire
                    };
                });

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new Info
                {
                    Title = "ASP NET .Identity Core Example"
                });

                var xmlFilePath = System.AppDomain.CurrentDomain.BaseDirectory + @"WebApiJwt.xml";
                x.IncludeXmlComments(xmlFilePath);
            });


            // ===== Add MVC ========
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env,
            ApplicationIdentityDbContext dbContext
        )
        {
            // ===== Create tables ======
            dbContext.Database.Migrate();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API");
            });

            // ===== Use Authentication ======
            app.UseAuthentication();
            app.UseMvc();         
        }
   }

我在执行此操作时面临 2 个问题:

  1. 首先,当我尝试添加迁移时,我收到了错误 An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: There is already an object named 'AspNetRoles' in the database.

  1. 我无法使用自定义个人资料信息更新AspNetUsers,我已尝试添加:

        // ===== Add Identity ========
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationIdentityDbContext>()
            .AddDefaultTokenProviders();
    

    也是ApplicationUser 类型,但AspNetUsers 表不会更新那些额外的列。

【问题讨论】:

    标签: c# asp.net-identity entity-framework-core


    【解决方案1】:

    简单浏览了一下,我注意到的第一件事是您应该使用 Generic IdentityDbContext:

    public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationUser>
    

    完整推荐场景:

    1. 定义您的 ApplicationUser 类:

    2.define context(这里我不喜欢硬编码连接字符串):

    public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationIdentityDbContext (DbContextOptions<ApplicationIdentityDbContext> options): base(options)
        {
        }
    }
    
    1. 在 appsettings.json 中定义连接字符串:

    “连接字符串”:{ "DefaultConnection": "这里是你的连接字符串" },

    1. 您应该在 ConfigureServices 中添加:

          // ===== Add our DbContext ========
          services.AddDbContext<ApplicationIdentityDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
      
          // ===== Add Identity ========
          services.AddIdentity<ApplicationUser, IdentityRole>()
              .AddEntityFrameworkStores<ApplicationIdentityDbContext>()
              .AddDefaultTokenProviders();
      
    2. 执行两条命令:

    添加迁移新迁移名称

    更新数据库

    1. 为避免迁移错误,您可能会看到以下文章:

    There is already an object named AspNetRoles in the database. (entity-framework-core)

    There is already an object named 'AspNetRoles' in the database

    https://github.com/aspnet/EntityFrameworkCore/issues/4649

    【讨论】:

    • 但是为什么我在执行迁移时得到 AspNetRoles 的异常已经存在?
    • 感谢您的意见,但我仍然无法解决迁移问题。
    【解决方案2】:

    如果数据库已初始化,使用迁移时注释掉Database.EnsureCreated()

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 2020-11-26
      • 2017-11-25
      • 2020-06-21
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      相关资源
      最近更新 更多