Search code examples
c#asp.net-coreasp.net-identityidentityserver4

Add custom unique property to my IdentityUser


I am using ASP.NET Core Identity to manage my application users. In order to store some additional properties, I created the class "ApplicationUser", which looks as follows:

public class ApplicationUser : IdentityUser
{
    public Guid CustomProperty { get; set; }
}

What I now want is that UserManager<ApplicationUser> gives me an error if the value of CustomProperty already exists in the database.

What is the best way to achieve this?

I already found this solution: https://stackoverflow.com/a/39125762/4046585. But it seems like a whole lot of work to do for such a simple requirement. Isn't there some kind of attribute that I can decorate the property with in order to accomplish this? Also the mentioned answer is almost 3 years old. So I'm not even sure if it works in ASP.NET Core 2.2


Solution

  • In EF core, you could specify that an index should be unique, meaning that no two entities can have the same value(s) for the given property(s).

    Add below code in your dbContext OnModelCreating and add migrations.

    modelBuilder.Entity<ApplicationUser>()
            .HasIndex(b => b.CustomProperty)
            .IsUnique();
    

    Refer to https://learn.microsoft.com/en-us/ef/core/modeling/indexes