如何将记录写入关联表?

时间:2015-08-01 19:50:01

标签: c# linq entity-framework-6

这是我的实体框架结构:

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 个答案:

答案 0 :(得分:1)

你不需要做任何奇特的工作。只是

  1. 使用Where / Single等
  2. 获取您要修改的实体/实体
  3. 修改实体/ enttities。
  4. 在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(); }

  5. 从概念上讲,它有助于记住,在大多数情况下,EF DbSets只是集合,需要明确保存更改以改变其成员的特殊警告。