Error while migration - There is already an object named 'AspNetRoles' in the database. (Entity Framework Core)

asp.net-identity c# entity-framework-core

Question

I am trying to add custom profile details using ASP.NET Identity Core. I have tried extending the IdentityUser class as follows:

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

This is my ApplicationDbContext which inherits IdentityDbContext:

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

And this is my startup.cs file:

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();         
        }
   }

I am facing 2 issues while doing this:

  1. First of all when I am trying to add migrations I am getting the error 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.

enter image description here

  1. I am not able to update AspNetUsers with the custom profile information, I have tried adding:

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

    of type ApplicationUser type also, but the AspNetUsers table is not updating those extra columns.

1
0
8/22/2018 4:58:13 AM

Popular Answer

Briefly looked through and the first thing I noticed is that your should use Generic IdentityDbContext:

public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationUser>

Full recommended scenario:

  1. define your ApplicationUser class:

2.define context (I am prefer not hard code connection string here):

public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationIdentityDbContext (DbContextOptions<ApplicationIdentityDbContext> options): base(options)
    {
    }
}
  1. define connection string in appsettings.json:

"ConnectionStrings": { "DefaultConnection": "here your connection string" },

  1. in ConfigureServices you should add:

        // ===== Add our DbContext ========
        services.AddDbContext<ApplicationIdentityDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
        // ===== Add Identity ========
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationIdentityDbContext>()
            .AddDefaultTokenProviders();
    
  2. execute two commands:

Add-Migration NewMigrationName

Update-Database

  1. to avoid migration errors you may see this articles:

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

2
8/22/2018 6:18:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow