简体   繁体   中英

Different user types with ASP.NET Core 1.1 Identity and Entity Framework Core

Using ASP.NET Core Identity with Entity framework Core i need to add different types of users in my app:

Let's say that i need two types of users: "Student" and "Teacher"; both of them are also ApplicationUsers since they have to be authenticated to access the app.

I have accomplish that creating two tables: one for Student and one for Teacher. Both tables are one-to-one related with the ApplicationUser table.

I'd like to know if this is correct or if i'm doing something wrong, because when updating the database with migrations it throws the error "FOREIGN KEY 'FK_Student_AspNetUsers_Id' in 'Student' table may cause cycles or multiple cascade paths. specify ON DELETE NO ACTION or UPDATE NO ACTION" . And, in any case, if it goes right, at the end i'd have an ApplicationUser class with two columns (one for StudentId and another for TeacherId), and one of them will always be null since an ApplicationUser can be a Student or a Teacher, but not both.

Here is my code so far:

public class ApplicationUser : IdentityUser<int>
{
    public string Name { get; set; }

    [ForeignKey("Teacher")]
    public int? TeacherId { get; set; }
    public virtual Teacher Teacher { get; set; }
    [ForeignKey("Student")]
    public int? StudentId { get; set; }
    public virtual Student Student { get; set; }
}

public class Student
{
    [Key, ForeignKey("User")]
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string MotherMaidenName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime EnrollmentDate { get; set; }

    public virtual ApplicationUser User { get; set; }
}

public class Teacher
{
    [Key,ForeignKey("User")]
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string MotherMaidenNAme { get; set; }

    public virtual ApplicationUser User { get; set; }
}

UPDATED : I've set TeacherId and StudentId as nullable, so the Error mentioned above is gone.

You shouldn't create different tables for each user type you have. You should create roles and assign that roles to a user. For example create a role student and a role teacher and assign them acording to your needs.

So I would say what you've done isn't a good design.

When you need to save additional values for a student/teacher than I would do something similar to your design. But I wouldn't add ID's for my student/teacher to my ApplicationUser class. I would simply add a UserId to my student/teacher class. So the design issue should be that you're trying to put that stuff into the ApplicationUser class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM