Search code examples
asp.netasp.net-mvcentity-frameworkasp.net-identityasp.net-identity-2

Using custom properties for AspNetUsers table in ASP.NET Identity


I use ASP.NET Identity 2.0 in an MVC application and there is a default table called AspNetUsers in order to keep user data with the columns below:

AspNetUsers:

Id
Email
EmailConfirmed
PasswordHash
... etc

I know that I can add custom properties to this Entity as Name, Surname, etc. to this AspNetUsers table. However, there are 2 types of users in my project: Student and Professor. Therefore I need to use different properties as shown below:

Student:

Id
Name
Surname
Email
StudentNumber
Department

Professor:

Id
Name
Email
Surname
Profession
RoomNumber

At this point I have a problem when combining these entities and I do not know how to combine them. Students and Professors are stored in AspNetUsers table and I think there is no need to define the same data as Email on different tables and it is better to use only the different properties in the Student and Professor tables as StudentNumber, RoomNumber, etc. When a user login to the system I think to use AspNetUsers table first and then get the detail data for the current user from the Student or Professor table. Is there a better approach for this situation? I think ASP.NET Identity is commonly used and many people need to store different detail properties for different type of users. Any help would be appreciated.


Solution

  • Here is another possible solution, though it is up to you to determine if it is a good fit for your needs. You can you Table per Hierarchy (TPH) for your model. First make your user class abstract and put all common properties in there:

    public abstract class ApplicationUser : IdentityUser
    {
        //snip
    
        //Common properties
        public string Name { get; set; }
        public string Surname { get; set; }
    }
    

    Now create your different user type classes and inherit from the base class:

    public class StudentUser : ApplicationUser
    {
        public string StudentNumber { get; set; }
    }
    
    public class ProfessorUser : ApplicationUser
    {
        public string Profession { get; set; }
    }