Samadhi Upeshala
Samadhi Upeshala

Reputation: 29

Change the action for DeleteBehavior.Restict exception

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.

Upvotes: 1

Views: 95

Answers (1)

Arjun Vachhani
Arjun Vachhani

Reputation: 1958

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));
}

Upvotes: 1

Related Questions