0

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

timnot90
  • 351
  • 1
  • 13

2 Answers2

2

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

Ryan
  • 19,118
  • 10
  • 37
  • 53
0

I'm guessing you want the CustomProperty to be sort of unique or something. You can use the DatabaseGenerated attribute to achieve that.

Decorate your property like below:

    public class ApplicationUser : IdentityUser
     { 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CustomProperty { get; set; }

 }

You can read more on that.

bolkay
  • 1,881
  • 9
  • 20
  • Is it really THAT simple...? :) – timnot90 May 07 '19 at 18:17
  • I tried this, but I still could insert two entries with the same value of `CustomProperty`. So I'm going with Xing Zous solution now. – timnot90 May 08 '19 at 08:02
  • @timnot90 Alright. I must have misinterpreted your question or something. I was thinking the `CustomProperty` is autogenerated. I would have suggested Xing's solution too. – bolkay May 08 '19 at 08:08