现在,此方法将删除已填写所有字段的职位发布。即使所有字段均未填写(接受空值),我也需要它来删除职位。这是 Controller 方法:
[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 的内容,请在 delete 方法之前进行 null 检查:
if (schedules != null)
{
// the foreach
}
...
if (shift != null) db.ShiftTime.Remove(shift);
...
if (other != null) db.JobOthers.Remove(other);
关于c# - 如何让我的删除方法接受空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545636/