0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Brian Rice
  • 3,107
  • 1
  • 35
  • 53
  • yeah I'm not surprised this doesn't work. Even with the same properties, it won't know that it can convert Person to Student. One idea is to serialize Person to a json string, and then de-serialize it as a Student. It would take two lines of code, and should be fast, – Casey Crookston Aug 22 '19 at 17:46
  • You could make a new interface, `IPerson`, and have `Student`, `Teacher`, and `Person` all implement `IPerson`. Then change your collection to a `List`. – Sam Axe Aug 22 '19 at 18:35
  • Also, you can not add a collection to another collection with the `Add` method. `Add` expects a single element. What you want is the `AddRange` method. – Sam Axe Aug 22 '19 at 18:37
  • You could use `ReinterpretCast` from [this answer](https://stackoverflow.com/a/42078952/2557128) but it is a type safety violation. – NetMage Aug 22 '19 at 19:25

1 Answers1

0

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240