我正在尝试从我的控制器测试删除方法。
我有以下测试用例:
[TestMethod()]
[DeploymentItem("Courses.sdf")]
public void RemoveCourseConfirmedTest()
{
CoursesController target = new CoursesController();
int id = 50;
ActionResult actual;
CoursesDBContext db = new CoursesDBContext();
Course courseToDelete = db.Courses.Find(id);
List<CourseMeet> meets = db.Meets.Where(a => a.courseID == id).ToList();
actual = target.RemoveCourseConfirmed(courseToDelete);
foreach (CourseMeet meet in meets)
{
Assert.IsFalse(db.Meets.Contains(meet));
}
Assert.IsFalse(db.Courses.Contains(courseToDelete));
}
这是控制器方法
[HttpPost, ActionName("RemoveCourse")]
public ActionResult RemoveCourseConfirmed(Course course)
{
try
{
db.Entry(course).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbUpdateConcurrencyException)
{
return RedirectToAction("RemoveMeet", new System.Web.Routing.RouteValueDictionary { { "concurrencyError", true } });
}
catch (DataException)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again.");
return View(course);
}
}
但是,当我运行测试用例时,出现以下异常。
System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
我通过调试器运行了测试,发现问题在以下行:
db.Entry(course).State = EntityState.Deleted;
我不确定为什么会这样。