Пример #1
0
        public static bool IsPrimaryKeyException(Exception e, out PrimaryKeyExceptionInfo pk)
        {
            // sample: Violation of PRIMARY KEY constraint 'PK_SomeTable'. Cannot insert duplicate key in object 'dbo.SomeTable'. 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;
        }
Пример #2
0
        public static bool IsPrimaryKeyException(Exception e, out PrimaryKeyExceptionInfo pk)
        {
            // sample: Violation of PRIMARY KEY constraint 'PK_SomeTable'. Cannot insert duplicate key in object 'dbo.SomeTable'. 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);
        }