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.