c# - 如何让我的删除方法接受空值?

标签 c# if-statement controller null

现在,此方法将删除已填写所有字段的职位发布。即使所有字段均未填写(接受空值),我也需要它来删除职位。这是 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/

相关文章:

MySql 条件

javascript - 使用 jquery 检查 css 的属性值

java - Spring Controller 中是否可以有handleRequest函数以及参数注释?

c# - Newtonsoft.JSON 序列化产生一个具有对象类型的唯一字符串

python - 比 If Else 更聪明

c# - 运行类 C# 中的所有方法

JavaFX 标签未使用 setText() 更新

php - CodeIgniter/胖模型/瘦 Controller

c# - “将应用程序与商店关联”选项未显示是 visual studio ultimate 2013 for windows phone 8.1 silverlight 项目

c# - 更改 WebResource.axd 的请求 url