繁体   English   中英

实体框架两个具有相同对象的表

[英]Entity Framework two tables with identical objects

我有两个具有相同属性的表,例如:

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

但是,实体框架不允许将相同的类用于不同的表。

因此,我改用:

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

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

但是,如果我从第三方检索,则有大量数据

List<Person> data;

我做不到

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

也不

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

有什么建议可以解决这个问题吗?

注意:这是一个简单的示例,它实际上用于大量的股价柱,性能是一个大问题,如果我能帮助的话,我不一定要实例化对象的许多副本。

我们需要有关如何创建List<Person>以获得完全有效答案的更多详细信息,但是如果您通过添加StudentTeacher对象来创建它,那么您应该能够在运行时强制转换实际上 Student的对象:

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

我还将使Person abstract因此您不得不使用一种具体类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM