Reputation: 371
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
Upvotes: 0
Views: 1645
Reputation: 20116
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
Upvotes: 2
Reputation: 1909
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.
Upvotes: 0