I'm trying to add a Required property for ApplicationUser (ASP.NET Identity, MVC5)
Here's a simple example:
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
}
The field is created in the database, but ends up NULLABLE
I expect the field to be NOT NULL.
Any idea how to get around this?
Table per Hierarchy (TPH) mapping is the default in Entity Framework Code First. This means that if FirstName isn't required in all the classes in the type hierarchy that share the same table, then the column cannot be non-null.
If you want the FirstName column to be non-nullable you could choose a different mapping strategy. If you use Table per Type (TPT) instead, then you will have one table for the IdentityUser (AspNetUsers by default) and another for ApplicationUser. As the FirstName now is unique to the ApplicationUser table it can be non-nullable.
To use TPT you can override the OnModelCreating method like this:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With