简体   繁体   中英

Multiple level inheritance. Entity Framework C#

I have been working with inheritance on Entity Framework 6 (code-first) with Visual Studio 2015. At this point I wanted to try Multiple Inheritance like this (This is a summary not the exactly syntaxt):

public abstract class Person {
    public String Name
    public String LastName
}

public class Teacher : Person {
    [Key]public int Id_Teacher
}

public class Student : Person {
    [Key] public int Id_Student
    public string code_s
}

public class ExchangeStudent : Student {
    [Key] public int Id_ExchangeStud
    public string HomeUniversity
}

I have made the first step that is create Person and the Child tables Teacher & Student, but when it comes to create the third child table it don't work.

I used TPC for the first step so in the Context I got DbSet of Students and Teachers.

Is there any way to implement the third table EXCHANGE STUDENT??

Thanks you so much.

If I understand correctly, your Model design should look like below,

    public class Person
    {
        [key] //No need to mention [key] annotation here, Because EF will automatically understand Id property will act as Primary Key.
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
    }

    public class Teacher: Person
    {

    }

    public class Student: Person
    {
        public string Code { get; set; }
    }

    public class ExchangeStudent : Student
    {

        public string HomeUniversity { get; set; }
    }

You have to avoid each [Key] properties in each child classes . B ase Class will have an Id property which will act as a PrimaryKey for the Table and all other child class.

If you follow the above, after applying the migration script into the Table, System will create a Table(Persons) with Discriminator column for the child class.

Hope this may help you to move forward!

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