我正在开发我的教程项目,我是实体框架的新手。
这是表格定义:
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个科目:历史,数学,物理。
我需要添加新学生并将学生与现有课程联系起来。
知道如何实施它?
提前谢谢。
答案 0 :(得分:2)
尝试以下代码: 取决于您是否要更新courseName或添加学生列表。
public void UpdateCourse(string courseName, List<Student> students)
{
var dbInstance = new EmployeeDBContext();
Course model = (from item in dbInstance.Courses
where item.CourseID = courseid
select item);
model.CourseName = courseName;
foreach(var item in students)
{
var currentStudent = from stud in dbInstance.Students
where stud.StudentId == item.StudentId;
if( currentStudent != null)
currentStudent.Name = item.Name;
else
dbInstance.Students.Add(new Student() {.StudentId = item.StudentId, .Name = item.Name});
};
dbInstance.SaveChanges();
}
public void CreateCourse(string courseName, List<Student> students)
{
var model = new Course();
model.CourseName = courseName;
model.Students = students;
var dbInstance = new EmployeeDBContext();
dbInstance.Courses.Add(model);
dbInstance.SaveChanges();
}
答案 1 :(得分:2)
如果你需要创建一个学生并为他添加一门课程(或更多课程),那么使用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();
}