Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default indexes in AspNetCore.Identity tables

I'm developing a multi-tenant application in ASP.NET Core 2.1. I'm utilizing AspNetCore.Identity.EntityFrameworkCore framework for user management. I want to add a unique index combining NormalizedName with TenantId in Role Table. Also, in the user table NormalizedUserName with TenantId in User table.

This doesn't let me create that index since identity creates a default unique indexes for Role table RoleNameIndex and UserNameIndex for User table. What is the best way to configure that in OnModelCreating method in EF Core?

 modelBuilder.Entity<User>().HasIndex(u => new { u.NormalizedUserName, u.TenantId }).HasName("UserNameIndex").IsUnique(true);
 modelBuilder.Entity<Role>().HasIndex(u => new { u.NormalizedName, u.TenantId }).HasName("RoleNameIndex").IsUnique(true);
like image 986
Aruna Avatar asked Aug 07 '18 15:08

Aruna


1 Answers

The fluent API currently does not provide a way to remove a previously defined index (like the indexes in question defined by the base OnModelCreating), but mutable entity metadata does via IMutableEntityType.RemoveIndex method.

It can be used like this:

modelBuilder.Entity<User>(builder =>
{
    builder.Metadata.RemoveIndex(new[] { builder.Property(u => u.NormalizedUserName).Metadata });

    builder.HasIndex(u => new { u.NormalizedUserName, u.TenantId }).HasName("UserNameIndex").IsUnique();
});

modelBuilder.Entity<Role>(builder =>
{
    builder.Metadata.RemoveIndex(new[] { builder.Property(r => r.NormalizedName).Metadata });

    builder.HasIndex(r => new { r.NormalizedName, r.TenantId }).HasName("RoleNameIndex").IsUnique();
});
like image 197
Ivan Stoev Avatar answered Oct 07 '22 11:10

Ivan Stoev