我正在做我的教程项目,我是实体框架的新手。
我有两个很多的关系表,我正在使用代码优先方法:
这是表的定义:
class EmployeeDBContext : DbContext
{
public EmployeeDBContext() : base("DefaultConnection") { }
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
}
//================================================My entities=================================================
public class Student
{
[Key]
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
课程表中包含3个科目:历史,数学,物理。
我需要添加新学生,并将该学生与现有课程联系起来。
知道如何实施吗?
如果您需要创建一个学生并向他添加一门课程(或多门课程),则使用EF的方式与用单词描述的方式相同...
using (var ctx= new EmployeeDBContext())
{
// Create a new student (and set some properties)
Student student = new Student()
{
StudentName = "Scott Tiger"
};
// Replace courseId with the course id that you need to add to the student
student.Courses.Add(ctx.Courses.Find(courseId));
// Add other courses if you need to
// Let's write the student to the DB
ctx.Students.Add(student);
ctx.SaveChanges();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句