Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to skip value cannot be null?

I have a data grid that contains record from the database. l 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 l 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. kindly assist.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading