public static bool IsForeignKeyException(Exception e, out ForeignKeyExceptionInfo fk) { // sample message: The DELETE statement conflicted with the REFERENCE constraint "FK_SomeTable_SomeFieldID". The conflict occurred in database "DBSome", table "dbo.SomeTable", column 'SomeFieldID'. 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 IsForeignKeyException(Exception e, out ForeignKeyExceptionInfo fk) { // sample message: The DELETE statement conflicted with the REFERENCE constraint "FK_SomeTable_SomeFieldID". The conflict occurred in database "DBSome", table "dbo.SomeTable", column 'SomeFieldID'. 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; }