Search code examples
c#entity-frameworkdowncast

Entity Framework two tables with identical objects


I have two tables that have identical properties, for example:

DbSet<Person> Students;
DbSet<Person> Teachers;

However Entity Framework does not allow the same class to be used for different tables.

So, instead I use:

DbSet<Student> Students;
DbSet<Teacher> Teachers;

public class Student : Person { }
public class Teacher : Person { }

However if I retrieve from a third party, a large set of data as

List<Person> data;

I am unable to do

Students.Add(data) <== compile time error unable to convert

nor

foreach (var item in data)
    Students.Add((Student)item); <== runtime error unable to cast

Any suggestions on a good way to handle this?

Note: this is a simplistic example it is actually used for large quantities of stock price bars and performance is a big issue and I don't necessarily want to be instantiating many, many copies of an object if I can help it.


Solution

  • We need more details on how you create the List<Person> for a completely valid answer, but if you create it by adding Student and Teacher objects, then you should be able to cast the ones that actually are Students at runtime:

    List<Person> people = new List<Person>();
    people.Add(new Student());
    people.Add(new Teacher());
    foreach(Student student in people.OfType<Student>())
    {
        Students.Add(student);
    }
    

    I would also make Person abstract so you are forced to use one of the concrete types.