Search code examples
c#.net-coreasp.net-identity

Can't drop unique index over NormalizedName using identity ef core


I'm trying to make the role unique per NormalizedName and other properties

I'm using asp .net core 3.1 What I'm trying is to drop the unique index over NormalizedName and make it over multiple properties

that is my dbContext

ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>

and this is my inject

services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {

                options.Tokens.EmailConfirmationTokenProvider = providerName;
                options.Tokens.PasswordResetTokenProvider = providerName;
                options.Tokens.ChangeEmailTokenProvider = providerName;
                options.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
            })
                .AddRoleValidator<TenantRoleValidator>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddTokenProvider<CustomTotpTokenProvider<ApplicationUser>>(providerName);

my ApplicationRole inherit from IdentityRole what i try


public void Configure(EntityTypeBuilder<ApplicationRole> builder)
        {
            builder.HasIndex(c => c.NormalizedName).IsUnique(false);
            builder.HasIndex(c => new { c.NormalizedName, c.SupplierId, c.CustomerId }).IsUnique(true);
        }

but unfortunately after Add-Migration by the reslt was

migrationBuilder.CreateIndex(
                name: "IX_AspNetRoles_NormalizedName_SupplierId_CustomerId",
                table: "AspNetRoles",
                columns: new[] { "NormalizedName", "SupplierId", "CustomerId" },
                unique: true);

What I expected was for him to update the index over NormalizedName


Solution

  • this removes index

    var index = modelBuilder.Entity<ApplicationRole>()
                .HasIndex(u => new { u.NormalizedName }).Metadata;
                var applicationUserType = modelBuilder.Entity<ApplicationRole>().Metadata.RemoveIndex(index.Properties);
    

    This should be done after calling base.OnModelCreating() to avoid it being recreated