Using Inheritance in Entity Framework

Posted on August 14, 2012 by Michael Roma

Below is an example of how to use table inheritance in Entity Framework. Note: All entities inherit from TableBase that contains a key value of id. Model

// Contact entity
public class Contact : TableBase
{
    // contact fields
    public string FirstName { get; set; }
    public string LastName { get; set; }        
}

// Faculty entity, inherit from contact
public class Faculty : Contact
{
    public string Focus { get; set; }
}

// Studen entity, inherit from contact
public class Student : Contact
{
    public int GraduationYear { get; set; }
}

Creating sample data and seeing results in SQL

public void CreateSample2()
{
    // purge data
    this.Database.ExecuteSqlCommand("delete from contacts");
    this.SaveChanges();

    // add faculty
    Faculty.Add(new Faculty 
        { FirstName = "Mike", LastName = "Smith", Focus = "CS" });
    Faculty.Add(new Faculty 
        { FirstName = "Jane", LastName = "O'Donnell", Focus = "Math" });
    Faculty.Add(new Faculty 
        { FirstName = "Matt", LastName = "James", Focus = "Biology" });

    // add students
    Students.Add(new Student 
        { FirstName = "Paul", LastName = "Jones", GraduationYear = 2013 });
    Students.Add(new Student 
        { FirstName = "Jennifer", LastName = "Allison", GraduationYear = 2016 });

    // commit
    this.SaveChanges();
}

/*
    select * from contacts
    id   FirstName      LastName       Focus          GraduationYear Discriminator
    ---- -------------- -------------- -------------- -------------- ------------- 
    1    Mike           Smith          CS             NULL           Faculty
    2    Jane           O'Donnell      Math           NULL           Faculty
    3    Matt           James          Biology        NULL           Faculty
    4    Paul           Jones          NULL           2013           Student
    5    Jennifer       Allison        NULL           2016           Student
*/  

Querying data

private void selectFacultyStudents()
{
    // get the db context
    using (var db = new Data.Db())
    {
        // get a list of contacts that are faculty
        var f = db.Contacts
            .OfType()
            .ToList();

        // traverse
        Console.WriteLine("Faculty:");
        foreach (var i in f)
        {
            Console.WriteLine(String.Format("{0}, {1}: {2}", i.LastName, i.FirstName, i.Focus));
        }


        // get a list of contacts that are students
        var s = db.Contacts
            .OfType()
            .ToList();

        // traverse
        Console.WriteLine("Students:");
        foreach (var i in s)
        {
            Console.WriteLine("{0}, {1}: {2}", i.LastName, i.FirstName, i.GraduationYear);
        }
    }
}
comments powered by Disqus