Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Create a DbContext class that inherits from IdentityDbContext. For example:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
  1. In the Startup.cs file, add the following code to configure Identity:
services.AddIdentity<ApplicationUser, ApplicationRole>(
        options =>
        {
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 8;
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
  1. Define your ApplicationUser and ApplicationRole classes:
public class ApplicationUser : IdentityUser<string>
{
    // add additional properties here
}

public class ApplicationRole : IdentityRole<string>
{
    // add additional properties here
}
  1. Configure the DbContext to have the desired tables and relationships:
protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.Claims)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.Roles)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationRole>()
        .HasMany(e => e.Claims)
        .WithOne(e => e.Role)
        .HasForeignKey(e => e.RoleId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationRole>()
        .HasMany(e => e.Users)
        .WithOne(e => e.Role)
        .HasForeignKey(e => e.RoleId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);
}
  1. Finally, use the ApplicationDbContext class to access the AspNetUsers and AspNetRoles tables:
var users = _context.Users.ToList();
var roles = _context.Roles.ToList();

You can then customize the data by adding additional properties to the ApplicationUser and ApplicationRole classes and modifying their respective table structures in the OnModelCreating method.