Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity How to I add a required property for a custom ApplicationUser?

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.

enter image description here

Any idea how to get around this?

like image 737
Kevin Radcliffe Avatar asked Feb 15 '23 18:02

Kevin Radcliffe


1 Answers

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");
}
like image 160
Olav Nybø Avatar answered Feb 19 '23 04:02

Olav Nybø