How to manage different types of Users with different properties on .NET Core 6

Viewed 40

For example I have two different user, Student and Admin.

They have common properties like Username, Email, Password, CreateDate, Role etc.

But Student has different or extra properties from Admin, for example Image, CvPath, Graduated School, Graduate Year etc. so how should I build my entity design on this.

3 Answers

You can create a base class which has the main properties. Both Student and Admin classes inherits from the base class User. The admin class will have the extra properies in it. You could also add some student-specific properties.

public class User
{
  public string Username {get; set;}
  public string Email {get; set;}
  public DateTime CreationDate {get; set;}
  // I am assuming you do not have a Role enum
  public string Role {get; set;}

}

public class Student : User
{
// You can just leave it empty or add something like Current year in school 
// maybe
}

public class Admin : User
{
  public string School {get; set;}
  public DateTime Graduate_Year {get; set;}
  public bool IsGraduated {get; set;}
  // and the reset of props you want for admin
}

I hope I helped you!

You have two options:

Option 1 : separate Users.cs entity to Admin.cs and Student.cs.

Option 2 : Put all properties you need in admin and student in Users.cs.

I suggest Option 1.

You may have heard of "favouring Composition over Inheritance" and so I wanted to put forward a case for the former.

Instead of inheriting the base class of User, you could include it in your Student and Admin classes, like so:

public class Student
{
    public User StudentUser { get; set; }
    public string Image { get; set; }
    public string CVPath { get; set; }
    public string GraduatedSchool { get; set; }
    public int GraduatedYear { get; set; }
}

And for Admin:

public class Admin
{
    public User AdminUser { get; set; }
    ... // Your admin properties here
}

With inheritance, any changes in your superclasses will impact the subclasses, and this can cause a cascade of changes. In addition, the inheritance hierarchy can become overly-complex and therefore onerous to maintain.

With composition you are still able to access the members of the 'parent' classes e.g. User in this case.

User user1 = new User();
Student student1 = new Student();

student1.StudentUser = user1;
student1.StudentUser.Username = "Miguel";
student1.StudentUser.Email = "Micheal.Coreleone@test.com";
student1.Image = "images/image1.png";

Here's a great post on the subject.

Related