There is a many to many relationship table. I get an error adding data to it.
Error:The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
public class Student
{
public Student()
{
this.isPassive = false;
Lessons = new HashSet<Lesson>();
}
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
public string Mail { get; set; }
public string Password { get; set; }
public Nullable<int> LessonCredit { get; set; }
public bool isPassive { get; set; }
public int AccountTypeID { get; set; }
//Navigation Property
public virtual AccountType AccountType { get; set; }
public virtual ICollection<Lesson> Lessons { get; set; }
}
public class Lesson
{
public Lesson()
{
Students = new HashSet<Student>();
this.isPassive = false;
}
public int ID { get; set; }
public string Name { get; set; }
public int Credit { get; set; }
public bool isPassive { get; set; }
public Nullable<int> TeacherID { get; set; }
//Navigation Property
public virtual Teacher Teacher { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
[HttpPost]
public ActionResult LessonSelection(int[] LessonChecked)
{
int loginStudentId = Convert.ToInt32(Session["PersonId"]);
Student loginStudent = _studentBLL.Get(loginStudentId);
for (int i = 0; i < LessonChecked.Length; i++)
{
Lesson lesson = _lessonBLL.Get(LessonChecked[i]);
loginStudent.Lessons.Add(lesson);
_studentBLL.Update(loginStudent);
}
return View();
}