型号1)
public class Student {
int StudentID {get;set;}
string FirstName {get;set;}
string LastName {get;set;}
ICollection courses = {get; set;}
}
模型2)
public class Course{
int CourseID {get;set;}
string CourseName {get;set;}
int CreditHours {get;set;}
}
模型3)
public class StudentCourse{
int StudentCourseID {get;set;}
int StudentID {get;set;}
int CourseID {get;set;}
}
现在我向数据库添加了一堆数据...
并且学生与类(class)之间的关系(一对多)丢失。
也就是说现在我数据库中只有三个基于上述模型的数据表
他们之间没有任何关系。
如果我创建另一个应用程序,请编写与上面的模型完全匹配的 3 个模型,并定义它们之间的一对多关系
学生和类(class)使用 Fluent API,这行得通吗?也就是说我能够关联已经存在的数据吗?
例如,
执行上述步骤并查询学生列表并执行 Student.courses.ToList(); 后具有匹配学生 ID 的类(class)是否会作为该查询的列表返回?
最佳答案
and the relationship between student to course (one to many) is lost.
该关系不起作用,因为您仅在其学生
端设置了链接。您还需要为 Courses
上的关系添加端点:
public class Student {
public virtual ICollection<Course> Courses { get; set; }
}
public class Course {
public virtual Student Student { get; set; }
}
这应该建立一对多关系。
尽管许多学生选修相同的类(class),所以我将其设置为多对多关系:
public class Student {
public virtual ICollection<Course> Courses { get; set; }
}
public class Course {
public virtual ICollection<Student> Students { get; set; }
}
我相信这应该消除对 StudentCourse 表的需要,但我在这一点上需要纠正。
现在,对于它们之间的链接(StudentCourse),您还需要正确构建在此链接上的关系:
public class StudentCourse
{
public int Id { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
}
关于c# - Entity Framework 对现有数据的流畅 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216751/