我有以下测试用例
[TestMethod()]
[DeploymentItem("Courses.sdf")]
public void RemoveCourseConfirmedTest()
{
CoursesController_Accessor target = new CoursesController_Accessor();
int id = 50;
ActionResult actual;
CoursesDBContext db = target.db;
Course courseToDelete = db.Courses.Find(id);
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
actual = target.RemoveCourseConfirmed(courseToDelete);
foreach (var meet in meets)
{
Assert.IsNull(db.Meets.find(meet));
}
Assert.IsNull(db.Courses.Find(courseToDelete.courseID));
}
从我的控制器测试以下方法。
[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);
}
}
我知道我应该使用Mock数据库....但是对于这个项目,我决定采用这种方法。
所以这发生了什么。当我运行实际的网站时,这个功能完全正常,并删除了课程和属于它的所有会议。
但是当我运行测试时,我得到以下异常
System.InvalidOperationException: The operation failed: The relationship could not be
changed because one or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null value. If the
foreign-key does not support null values, a new relationship must be defined, the foreign-
key property must be assigned another non-null value, or the unrelated object must be
deleted.
如果我从测试中注释掉以下行,那么这是更有趣的部分
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
并用以下内容替换循环:
foreach (var meet in db.Meets.ToList())
{
Assert.IsFalse(meet.courseID == courseToDelete.courseID);
}
我没有任何例外,测试用例也没有。
我是否遗漏了有关Entity Framework的内容,或者这是一个错误?
答案 0 :(得分:0)
这已经有一段时间了。我仍然无法找到一个明确的答案,但更多地使用MVC和EF我认为发生的事情是,一旦我执行该行
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
会议被加载到对象管理器中,因此当删除父对象时,不再引用父课程。