.Net Core : ASP.NET Membership - Identity User - Setup

.Net Core : ASP.NET Membership - Identity User - Setup



1. install nuget package - Microsoft.AspNetCore.Identity.EntityFrameworkCore

2. inherit DbContext class with IdentityDbContext
e.g., public class AppDbContext : IdentityDbContext

3.Configure identity in statup file, as below,
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));

            services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<AppDbContext>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddScoped<IEmployeeRepository, EmployeeRepository>();
        }

4. add "app.UseAuthentication();" in Configure method before "app.UseMvc();".

5. Do datamigration using
Add-Migration "AddIdentity"

6. If you will get error like "The entity type 'IdentityUserLogin<string>' requires a primary key to be defined."
then 
goto appDbContext class and do changes in OnModelCreating method as below,
base.OnModelCreating(modelBuilder);

7. Now run again Add-Migration "AddIdentity"

8. then run Update-Database

9. Finally you can see there are some tables name start with "ASPNet" are added in database.

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment