现在这个方法会删除一个已经填写了所有字段的职位。我需要它来删除这个职位,即使没有填写所有字段(接受空值(。以下是控制器方法:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id) // triggered when Delete "Job Title" is pressed
{
Job job = db.Jobs.Find(id); // finds Job to delete in Jobs table
ShiftTime shift = db.ShiftTime.Find(id); // finds shifttimes attached to Job being deleted in ShiftTimes table
JobOther other = db.JobOthers.Find(id); // finds JobsOthers attached to Job being deleted in JobOthers table
var schedules = db.Schedules.Where(x => x.Job.JobIb == id); // finds list of schedules attached to Job being deleted in Schedules table
foreach (Schedule schedule in schedules) // iterates through list of schedules attached to Job being deleted....
{
db.Schedules.Remove(schedule); // ...and removes schedules
}
db.ShiftTime.Remove(shift); // removes ShiftTimes
db.JobOthers.Remove(other); // removes JobOthers
db.Jobs.Remove(job); // removes actual Job
db.SaveChanges(); // finally saves changes to each table
return RedirectToAction("Index"); // returns to "Index" list of Jobs
}
我想我必须加入一些if/else语句,但我尝试了很多不同的变体,但都无济于事。
我的理解是,对于给定的id
,总是有一个job
,但可能没有其他对象shift, other, schedules
。要让job
在其他为null的情况下删除,请在删除方法之前进行null检查:
if (schedules != null)
{
// the foreach
}
...
if (shift != null) db.ShiftTime.Remove(shift);
...
if (other != null) db.JobOthers.Remove(other);
您尝试过吗:
db.Entry(job).State = EntityState.Deleted;
而不是
db.Jobs.Remove(job);