I’m creating a database using entity framework code first and I’m having some issues with the database/POCO design. My problem is with inheritance.
My system has two main user roles Lecturer and Student. I have a base User class which contains Id, Logon, Role (identifying them as either lecturer or student), Forename and Surname. If the user is a Lecturer then they also have a Tags Property (relationship) associated with them. If the user is a Student then they have a year and a degree type property.
Both types of users can create projects. A project has a proposer. What i want is to be able to get the Lecturer or Student type back from Project.Proposer but i can’t seem to do that. I’m also not sure if Project.Proposer should be of type User (the base class) in the project class, whether i can use a interface (with code first) or what.
I would appreciate any guidance or ideas people could give me, I’ve tried many variations but none seem to give me the desired result. Note: I am trying to avoid having a user class that has redundant data so i don’t want the user class to contain the fields for lecturers and students.
The way todo this is properly in EF4 CodeFirst is to have a
Proposerproperty of typeUseron the project.After retrieving the project the Proposer will have the correct type, but the value will be boxed as
User. In order to figure out what actual the actual type is you can use theiskeyword like this:This is the datastructure I would suggest:
There are other ways to structure this, like introducing a hierachy for the projects by using classes like
LecturerProjectStudentProjectand move theProposerwith the correct type into the those classes, but this is not recommended. Since you will always have to handle these project classes separately. For example when retrieving the name of the project and it’s proposer. Since the base project class does not have a proposer property anymore you need to have the same query twice. I hope I could illustrate the issues that arise when using this approach.The next question you need to ask yourself is, do you care how the data is saved in the db? SInce there are 3 ways of doing this for classes with inheritance:
One word of advice. If you are not planning on storing millions of records, don’t mind how it is actually stored in the db.
Table per Hierarchyis by far the easiest to use, especially in the beginning, also it’s the default.