Skip to content

Instantly share code, notes, and snippets.

@volkanceylan
Created January 7, 2016 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volkanceylan/dd058b69cdd5e9eb3a77 to your computer and use it in GitHub Desktop.
Save volkanceylan/dd058b69cdd5e9eb3a77 to your computer and use it in GitHub Desktop.
using Serenity.Data;
using System;
using System.Data.SqlClient;
namespace Serenity.Services
{
public class DeleteRequestHandlerFK<TRow> : DeleteRequestHandler<TRow>
where TRow: Row, IIdRow, new()
{
protected override void ExecuteDelete()
{
try
{
base.ExecuteDelete();
}
catch (Exception e)
{
ForeignKeyExceptionInfo fk;
if (SqlExceptionHelper.IsForeignKeyException(e, out fk))
throw new ValidationError(String.Format("Can't delete. Table '{0}' has related records!", fk.TableName));
throw;
}
}
}
}
using System;
using System.Data.SqlClient;
namespace Serenity.Services
{
public class ForeignKeyExceptionInfo
{
public string TableName { get; set; }
}
public class PrimaryKeyExceptionInfo
{
public string TableName { get; set; }
}
public static class SqlExceptionHelper
{
public static bool IsForeignKeyException(Exception e, out ForeignKeyExceptionInfo fk)
{
// örnek mesaj: The DELETE statement conflicted with the REFERENCE constraint "FK_AileBirey_DogumYeriIlID". The conflict occurred in database "DBPersonel", table "dbo.AileBirey", column 'DogumYeriIlID'.
var sql = e as SqlException;
if (sql != null && sql.Errors.Count > 0 && sql.Errors[0].Number == 547)
{
var msg = sql.Errors[0].Message;
fk = new ForeignKeyExceptionInfo();
fk.TableName = "???";
var s1 = ", table \"";
var idx = msg.IndexOf(s1);
if (idx >= 0)
{
idx += s1.Length;
var idx2 = msg.IndexOf("\", column", idx + 1);
if (idx2 >= 0)
{
fk.TableName = msg.Substring(idx, idx2 - idx);
if (fk.TableName.StartsWith("dbo."))
fk.TableName = fk.TableName.Substring("dbo.".Length);
}
}
return true;
}
fk = null;
return false;
}
public static bool IsPrimaryKeyException(Exception e, out PrimaryKeyExceptionInfo pk)
{
// örnek mesaj: Violation of PRIMARY KEY constraint 'PK_Unvan'. Cannot insert duplicate key in object 'dbo.Unvan'. The duplicate key value is (7005950).
var sql = e as SqlException;
if (sql != null && sql.Errors.Count > 0 && sql.Errors[0].Number == 2627)
{
var msg = sql.Errors[0].Message;
pk = new PrimaryKeyExceptionInfo();
pk.TableName = "???";
var s1 = "in object '";
var idx = msg.IndexOf(s1);
if (idx >= 0)
{
idx += s1.Length;
var idx2 = msg.IndexOf("'.", idx + 1);
if (idx2 >= 0)
{
pk.TableName = msg.Substring(idx, idx2 - idx);
if (pk.TableName.StartsWith("dbo."))
pk.TableName = pk.TableName.Substring("dbo.".Length);
}
}
return true;
}
pk = null;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment