例如,採用以下數據庫表格:Students,Courses和StudentsCourses。如何通過實體框架檢查多對多表格以複製
我如何在實體框架中確保爲學生添加新課程時,課程還不存在?這對我來說意味着檢查StudentCourses表。
我是否需要直寫sql來檢查?
例如,採用以下數據庫表格:Students,Courses和StudentsCourses。如何通過實體框架檢查多對多表格以複製
我如何在實體框架中確保爲學生添加新課程時,課程還不存在?這對我來說意味着檢查StudentCourses表。
我是否需要直寫sql來檢查?
的方法,你可能沒有StudentsCourse
實體。我喜歡這種模式添加到多對多的關係:
public Student
{
private _Courses = new List<Course>();
public int ID { get; set; }
public virtual ICollection Courses
{
get { return _Courses; }
protected set { _Courses = value; }
}
public void AddCourse(Course course)
{
//And you can add your duplicate check here
if(!Courses.Any(c => c.ID == course.ID))
Courses.Add(course);
}
}
不幸的是,Courses
屬性不是隻讀集合,因此不會防止有人繞過這個方法用在其他地方:
student.Courses.Add(course);
但隨後在其他的答案中建議的方法不會阻止,要麼
using (var context = new StudentContext()
{
var alreadyExists = context.StudentsCourses.Any(x => x.StudentId == studentId && x.CourseId == courseId);
}
BenjaminPaul的答覆工作非常WEL。另一個選擇是嘗試和檢索你的學生,如果它不存在,創建一個新的。
如果你有一個簡單的多對多的關係,您可以創建這樣
public StudentCourse CreateOrUpdate(VM_StudentCourse studentCourse)
{
StudentCourse dbStudentCourse;
using (var context = new StudentContext()
{
dbStudentCourse = context.StudentsCourses.FirstOrDefault(x => x.StudentId == studentCourse.studentId && x.CourseId == studentCourse.courseId);
If (dbStudentCourse == null)
{
dbStudent = new StudentCourse();
dbStudent.StudentId = studentCourse.StudentId;
dbStudent.CourseId = studentCourse.CourseId;
context.Add(dbStudent);
}
dbStudent.OtherProperty1 = studentCourse.SomeProp;
dbStudent.OtherProperty2 = studentCourse.SomeOtherProp;
context.SaveChanges();
}
return dbStudentCourse;
}
你的意思是像'StudentsCourses.Where(X => x.StudentId == studentId && x.CourseId == courseId)'? – Ric
但是StudentsCourses不在導航屬性中。 – Rod
那麼你實例化上下文然後查詢上下文,按照下面的答案! – Ric