Skip to content

Instantly share code, notes, and snippets.

@JohnRanger
Last active January 7, 2016 16:10
Show Gist options
  • Save JohnRanger/ed3ec72b9d845b53247f to your computer and use it in GitHub Desktop.
Save JohnRanger/ed3ec72b9d845b53247f to your computer and use it in GitHub Desktop.
DeleteRequestHandlerFK.cs, handling foreign key exception messages individually for different tables
// *** All credits for the base idea to JajQ / Volkan Ceylan ***
using Serenity.Data;
using System;
using System.Data.SqlClient;
using <your solution name>; // Enter the namespace of your solution here
namespace Serenity.Services
{
public class DeleteRequestHandlerFK<TRow> : DeleteRequestHandler<TRow>
where TRow: Row, IIdRow, new()
{
protected override void ExecuteDelete()
{
try
{
base.ExecuteDelete();
}
catch (Exception e)
{
string OutputMessage = string.Empty;
ForeignKeyExceptionInfo fk;
if (SqlExceptionHelper.IsForeignKeyException(e, out fk))
switch ((Row.Table.ToLower() + "--" + fk.TableName.ToLower()))
{
case "[dbo].[supplier]--delivery": // *** Replace "[dbo].[supplier]" with the table associated with the entity where the exception is thrown and replace "delivery" with the foreign table ***
OutputMessage = "Sorry, but you cannot delete a supplier when this supplier is still used within a delivery. No delete has occured"; // *** Replace with your individual error mesage ***
break;
default:
OutputMessage = String.Format("Sorry, but you cannot delete this. Table '{0}' has related records!", fk.TableName);
break;
}
throw new ValidationError(OutputMessage);
throw;
}
}
}
}
@JohnRanger
Copy link
Author

then, within your xyzRepository.cs files, replace the line:
private class MyDeleteHandler : DeleteRequestHandler { }

with

private class MyDeleteHandler : DeleteRequestHandlerFK { }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment