我有两个非常简单的类。
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
表,无法区分它们。
有什么想法吗?
答案 0 :(得分:8)
有两种方法可以做到这一点;
首先:在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; }
}
答案 1 :(得分:1)
分为两个不同的班级,然后用Person继承它们,因为所有的老师和学生都是人,但不是所有人都是老师和学生。
public class Person
{
}
public class Teacher : Person
{
}
public class Student : Person
{
}
我希望这会有所帮助
答案 2 :(得分:0)
答案 3 :(得分:0)
情况稍有不同(当类持有对两个相同对象的引用时),但可能会有所帮助:
public class Mission
{
//DB objects
public int Id { get; set; }
public int SourceLocationId {get; set}
public int DestinationLocationId {get; set}
//Virtual objects
public virtual Location SourceLocation { get; set; }
public virtual Location DestinationLocation { get; set; }
}
public class Location
{
//DB objects
public int Id {get;set;}
//Virtual objects
public virtual ICollection<Mission> SourceMissions { get; set; }
public virtual ICollection<Mission> DestinationMissions { get; set; }
}
然后您要做的就是在 OnModelCreating 中正确绑定它:
modelBuilder.Entity<Mission>()
.HasOptional(m => m.SourceLocation) //Optional or Required
.WithMany(sm => sm.SourceMissions)
.HasForeignKey(to => to.SourceLocationId);
modelBuilder.Entity<Mission>()
.HasOptional(m => m.DestinationLocation) //Optional or Required
.WithMany(sm => sm.DestinationMissions)
.HasForeignKey(to => to.DestinationLocationId);
答案 4 :(得分:-1)
让两个单独的表中的教师和学生从抽象基础继承:
size_t readWifDataAsSever(char* reqData, size_t maxLen) {
if (len > 0) {
size_t activeLength = len < maxLen ? len : maxLen;
for(size_t i = 0 ; i < activeLength ; i++) {
reqData[i]=(char)buffer[i];
}
return activeLength;
} else {
reqData[0] = '\0';
return 0;
}
}