Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

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

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.

Upvotes: 0

Views: 2691

Answers (2)

G3k0S
G3k0S

Reputation: 35

If database was initialized, when you use migration comment out Database.EnsureCreated();

Upvotes: 0

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

Upvotes: 2

Related Questions