1

I want to restrict delete action for the entities with foriegn key dependencies. To do that I have this code in DbContext.

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder); 

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            {
                relationship.DeleteBehavior = DeleteBehavior.Restrict;
            }
}

In my controller action I have this code.

public async Task<IActionResult> Delete(int? id)
        {
            var departmentDto = await GetAsync(p => p.Id == id);
            if (departmentDto == null)
            {
                return NotFound();
            }

            return View(departmentDto);
        }

        // POST: Departments/5/Delete
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Route("{id:int:min(1)}/Delete")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            await DeleteAsync(p => p.Id == id);

            return RedirectToAction(nameof(Index));
        }
    }
}

So far I did this without error. Now the question is I want to set my own message in 'deletebehavior.restrict' and return to index insted of exception error. How can I do that? Please help me.

Samadhi Upeshala
  • 29
  • 1
  • 1
  • 7

1 Answers1

1

you can catch the exception and provide a proper error message

// POST: Departments/5/Delete
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Route("{id:int:min(1)}/Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    try
    {
        await DeleteAsync(p => p.Id == id);
    }
    catch(InvalidOperationException e)
    {
        return new BadRequestObjectResult("child exists for department"); // can return custom error object also
    }
    return RedirectToAction(nameof(Index));
}
Arjun Vachhani
  • 1,761
  • 3
  • 21
  • 44
  • what exception you are getting? – Arjun Vachhani Nov 15 '19 at 10:01
  • I tried your cide with a small modification and now it's working. public async Task DeleteConfirmed(int id) { try { await DeleteAsync(p => p.Id == id); } catch (DbUpdateException e) { return new BadRequestObjectResult("child exists for department"); // can return custom error object also } return RedirectToAction(nameof(Index)); } Thanks a lot sir. – Samadhi Upeshala Nov 18 '19 at 06:26
  • Can I make this with as an alert and redirect to Index page? – Samadhi Upeshala Nov 18 '19 at 06:28
  • handle ajax error response, alert and what not in javascript. see https://stackoverflow.com/questions/1637019/how-to-get-the-jquery-ajax-error-response-text – Arjun Vachhani Nov 18 '19 at 06:54