I use Entity Framework Core and SQL Server in my application. I am very familiar with foreign keys but I would like to learn the correct way to give a foreign key to an entity which is based on a type.
For example:
Parent class AppUser:
CREATE TABLE AppUser
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
Name VARCHAR(255) NOT NULL,
UserTypeId SMALLINT NOT NULL -- !This is the important part for me! if 0 = Student if 1 = Teacher
);
CREATE TABLE Student
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
AppUserId INT NOT NULL,
CONSTRAINT FK_Student_AppUser FOREIGN KEY (AppUserId)
REFERENCES AppUser(Id)
);
CREATE TABLE Teacher
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
AppUserId INT NOT NULL,
CONSTRAINT FK_Student_AppUser FOREIGN KEY (AppUserId)
REFERENCES AppUser(Id)
);
My question: is there a better way to have this relationship. Because in Entity Framework, when I try to get a user, I always need to check for the TypeId and have an if else block for the type, then make the query on the table student or teacher. Any advice would be great. Thanks!
UserTypeIdcolumn- what is its purpose? - MultiValidation