描述了关系多对多数据关系。
现在如何在CourseInstructo
上执行插入,删除和更新?
对于一对一的关系我这样做:
var context= new Modle2();
var course= new Course() {title="math",...};
context.Course.addObject(course);
context.SaveChanges()
答案 0 :(得分:0)
您可以在任一端使用导航属性来操纵多对多关系。 例如,
using (var context = new Model2())
{
int courseID = 4022;
var course = (from c in context.Courses
where c.CourseID == courseID
select c).First();
int personID = 17;
var instructor = (from p in context.Person
where p.PersonID == personID
select p).First();
course.Person.Add(instructor);
// alternatively, this will also do - instructor.Course.Add(course);
context.SaveChanges();
}
要删除,请使用类似的逻辑 - 例如,
using (var context = new Model2())
{
int courseID = 4022;
var course = (from c in context.Courses
where c.CourseID == courseID
select c).First();
int personID = 17;
var instructor = (from p in context.Person
where p.PersonID == personID
select p).First();
course.Person.Remove(instructor);
context.SaveChanges();
}
更新对于多对多关系没有意义 - 它实质上是添加和删除组合。