When designing a data table, if you set some columns to relate to other table foreign keys, then if you add to it, modify the operation, its associated table if there is no matching record error, or in its associated table to delete, will also error, this is the role of foreign key constraints, of course, in addition to foreign keys there are many constraints, not discussed here, This article is mainly about how to determine whether the SQL Reference constraint exception, so that the SQL complex error can be better converted to the user can understand the friendly hints.
Extend exception to determine whether exception is a SQL Reference constraint exception method (Issqlreferenceconstraintexception):
Public Static BOOLIssqlreferenceconstraintexception ( ThisException except) { varBaseex =except. GetBaseException (); if(Baseex isSqlException) { stringMessage = (Baseex asSqlException). Message; if(Message. ToLower (). Contains ("reference Constraint")) { return true; } Else { return false; } } Else if(Baseex! =NULL&&!Object. ReferenceEquals (except, Baseex))//If the base class is not empty and does not equal the exception itself, proceed back to the survey to find {returnissqlreferenceconstraintexception (Baseex); } return false; }
The native SQL error message is as follows:
The DELETE statement conflicted with the REFERENCE constraint "fk_dbo. Category_dbo. User_lasteditorid ". The conflict occurred in database "Mtem", table "dbo. Category ", column ' Lasteditorid '.
The statement has been terminated.
The extension method shows our predefined error message, which is called as follows:
Public voidRemove (intUserID) {User User= This. Repository. Get (t=>t.id==UserID); if(User! =NULL) { Try { This. Repository. Remove (User,true); } Catch(Exception ex) {if (ex. Issqlreferenceconstraintexception ())//judged to be a referential constraint error, then directly throws our custom error {Throw NewException ("the account has other business records associated with it and is prohibited from deletion! If you confirm that the account is stopped, you can set it to disabled. "); } } } Else { Throw NewException ("The account information does not exist or has been deleted! "); } }
Extend exception to determine if exception is a SQL Reference constraint exception Method!