Override default indexes in AspNetCore.Identity tables
Asked Answered
G

2

9

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);
Glossitis answered 7/8, 2018 at 15:0 Comment(0)
S
20

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();
});
Sacramentalist answered 7/8, 2018 at 15:36 Comment(0)
N
0

Don't think you can actually, unless you don't call base.OnModelCreating in your override. However, you'd then be responsible for all the Identity fluent config. You can see what you're dealing with here on Github.

The only thing to be aware of, if you go down that path, is that you'll need to watch for changes to the fluent config and make sure you add those into yours as they are introduced.

Nogas answered 7/8, 2018 at 15:9 Comment(1)
Yes. Actually I'm overriding onModel Creating method for the changes.Glossitis

© 2022 - 2024 — McMap. All rights reserved.