Ask Your Question
1

How to change the default table names for identity in an override manner?

asked 2021-06-18 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-28 10:00:00 +0000

devzero gravatar image

To change default table names for identity in an override manner, you need to follow these steps:

  1. Create a new class file in your project and name it IdentityConfig.cs.

  2. Inside the IdentityConfig class, add the following code:

using Microsoft.AspNet.Identity;

namespace YourNamespace.Config
{
    public class IdentityConfig
    {
        public static void Configure(IdentityFactoryOptions<AppUserManager> options)
        {
            options.UserValidator = new UserValidator<AppUser>(options.UserManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            options.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
                RequireNonLetterOrDigit = false
            };

            options.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/Login");
            options.Cookies.ApplicationCookie.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
            options.Cookies.ApplicationCookie.CookieName = ".YourIdentityApplicationCookie";

            options.UserManager.UserTokenProvider = new DataProtectorTokenProvider<AppUser>(sampleDataProtectionProvider.Create("ASP.NET Identity"))
            {
                TokenLifespan = TimeSpan.FromHours(3)
            };

            options.UserManager.ClaimsIdentityFactory = new AppClaimsIdentityFactory();
        }
    }
}

Here, specify the table names for identity tables in the AppDbContext class file.

public partial class AppDbContext : IdentityDbContext<AppUser, AppRole, string, AppUserLogin, AppUserRole, AppUserClaim>
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<AppUser>(entity =>
        {
            entity.ToTable("Users");
            entity.Property(e => e.Id).ValueGeneratedOnAdd().HasColumnName("UserId");
            entity.HasMany(e => e.Claims).WithOne().HasForeignKey(e => e.UserId).IsRequired();
            entity.HasMany(e => e.Logins).WithOne().HasForeignKey(e => e.UserId).IsRequired();
            entity.HasMany(e => e.Roles).WithOne().HasForeignKey(e => e.UserId).IsRequired();
        });

        modelBuilder.Entity<AppRole>(entity =>
        {
            entity.ToTable("Roles");
            entity.Property(e => e.Id).ValueGeneratedOnAdd().HasColumnName("RoleId");
            entity.HasMany(e => e.Claims).WithOne().HasForeignKey(e => e.RoleId).IsRequired();
            entity.HasMany(e => e.Users).WithOne().HasForeignKey(e => e.RoleId).IsRequired();
        });

        modelBuilder.Entity<AppUserRole>(entity =>
        {
            entity.ToTable("UserRoles");
            entity.HasKey(e => new { e.UserId, e.RoleId });
            entity.HasOne(e => e.Role).WithMany(e => e.UserRoles).HasForeignKey(e => e.RoleId).IsRequired();
            entity.HasOne(e => e.User).WithMany(e => e.UserRoles).HasForeignKey(e => e.UserId).IsRequired();
        });

        modelBuilder.Entity<AppUserClaim>(entity =>
        {
            entity.ToTable("UserClaims");
            entity.Property(e => e.Id).ValueGeneratedOnAdd().HasColumnName("UserClaimId");
            entity.HasIndex(e => e.UserId);
        });

        modelBuilder.Entity<AppUserLogin>(entity =>
        {
            entity.ToTable("UserLogins");
            entity.HasKey(e => new { e.LoginProvider, e.ProviderKey });
            entity.Property(e => e.ProviderDisplayName).HasMaxLength(40);
            entity.HasIndex(e => e.UserId);
        });
    }
}
  1. Modify the startup.cs to register the IdentityConfiguration file in the ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
    // Other services
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddIdentity<AppUser, AppRole>(options =>
    {
        IdentityConfig.Configure(options);
    })
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

    // Other configurations
}
  1. Build and run the application. Identity will now use the names specified in the OnModelCreating method of the AppDbContext class.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-18 11:00:00 +0000

Seen: 8 times

Last updated: Jan 28 '22