How to get my delete method to accept null values?

Viewed 58

Right now this method will delete a job post that has all the fields filled in. I need it to delete the job even if all the fields are not filled in (accept null values). Here is the controller method:

        [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 

        }

I'm thinking that I'll have to include some if/else statements but I have tried so many different variations to no avail.

2 Answers

My understanding is that for a given id there is always a job but there may not be the other objects shift, other, schedules. To get job to delete with others being null, do a null check before the delete methods:

if (schedules != null) 
{ 
    // the foreach 
}
...
if (shift != null) db.ShiftTime.Remove(shift);
...
if (other != null) db.JobOthers.Remove(other);

Have you tried:

db.Entry(job).State = EntityState.Deleted;

instead of

db.Jobs.Remove(job);
Related