Search code examples
asp.net-core

How to skip value cannot be null?


I have a data grid that contains record from the database. I can save data into database without uploading image to its folder and the column for the image name in the database would be empty. When I tried to delete any row that have an empty image name column it display an error:

System.ArgumentNullException: 'Value cannot be null. (Parameter 'path3')'.

I want to ignore this error so that l can delete record from the database that does not have a corresponding image in its folder.

public IActionResult Delete([FromBody] ICRUDModel<Employee> value)
{
    Employee order = _context.Employee.Where(c => c.EmployeeId == (int)value.key).FirstOrDefault();
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Photos", order.Passport!);

    if (System.IO.File.Exists(filePath))
    {
        System.IO.File.Delete(filePath);
    }
                   
    _context.Employee.Remove(order);
    _context.SaveChanges();
    return Json(order);
}    
Id EmployeeName Position ImageName
1 Annah Admin Assistant annah.png
2 Maria Manager

Expected output

Id EmployeeName Position ImageName
1 Annah Admin Assistant annah.png

Solution

  • The exception is due to the 3rd parameter of Path.Combine() being null, ie, order.Passport!.

    You can skip the file deletion and still delete the Employee record by checking for the order.Passport for null like below. You may want to consider handling the case where Employee order is null, too.

    public IActionResult Delete([FromBody] ICRUDModel<Employee> value)
    {
        Employee order = _context.Employee.Where(c => c.EmployeeId == (int)value.key).FirstOrDefault();
        
        if (order.Passport is not null) 
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), 
                   "wwwroot/Photos", 
                   order.Passport!);  // this will not be null here
            System.IO.File.Delete(filePath);
        }
                       
        _context.Employee.Remove(order);
        _context.SaveChanges();
        return Json(order);
    }