如何将记录写入关联表

本文关键字:关联 记录 | 更新日期: 2023-09-27 18:05:58

这是我的实体框架结构:

namespace TestMigration2
{
    class EmployeeDBContext : DbContext
    {
        public EmployeeDBContext() : base("DefaultConnection") { }
        public DbSet<Course> Courses { get; set; }
        public DbSet<Student> Students { get; set; }
    }

    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; }
    }
}

如何在linq的帮助下编写与特定学生相关的课程?

如何将记录写入关联表

你不需要做任何花哨的工作。

  1. 获取您希望修改的实体/实体使用Where/Single等
  2. 修改实体/实体
  3. 调用保存更改在您的DbContext。

    using (var db = new EmployeeDbContext()) //NOTE: FOR THE LOVE OF GOD USE A REPOSITORY OR CONTEXT FACTORY OR SOMETHING TO MAKE SURE THAT THE LIFETIME OF YOUR CONTEXT IS MANAGED CORRECTLY. { var student = db.Students.Single(student => student.Id == 1); //Use your own condition here. foreach(var course in db.Courses.Where(course=>course.Id == 1)) //Use your own condition here { student.Courses.Add(course); } db.SaveChanges(); }

从概念上讲,这有助于记住,在大多数情况下,EF dbset只是集合,需要特别注意的是,您需要显式保存更改以改变其成员。