我有这两个非常简单的类。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
}
public class Group
{
public int Id {get;set;}
public ICollection<Person> Teachers { get; set; }
public ICollection<Person> Students { get; set; }
}
我希望EF将
Teachers
与Students
分开,但是它们都混杂在Person
表中,无法区分它们。有任何想法吗?
最佳答案
有两种方法可以做到这一点:
首先:在Person
对象中使用标签或枚举
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
public bool IsFaculty { get; set; }
}
或者
public enum PersonType { Teacher, Student };
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
public PersonType PropPersonType { get; set; }
}
第二个:面向继承的工作对象。我偏爱此方法,因为如果要扩展它,它易于管理和扩展。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
}
public class Student : Person
{
public int Year { get; set; }
// other student related fiels.
}
public class Teacher : Person
{
public List<Course> Courses { get; set; }
// other teacher related fields
}
然后,您的
Group
是public class Group
{
public int Id {get;set;}
public ICollection<Teacher> Teachers { get; set; }
public ICollection<Student> Students { get; set; }
}
关于c# - Entity Framework 中相同类型的多个集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22628139/