Extended Exception, added the method to determine whether the Exception is an SQL reference constraint Exception !, Predictionsql
When designing a data table, if you set some columns as foreign keys associated with other tables, if you add or modify the columns, if the associated table does not have a matched record, an error is returned, or an error is returned when the associated table is deleted. This is the role of the foreign key constraint, of course, there are many constraints besides Foreign keys, which we will not discuss for the moment. This article mainly describes how to judge whether the SQL reference constraint is abnormal, in this way, you can better convert complicated SQL errors into friendly prompts that you can understand.
Extended Exception, added the method to determine whether the Exception is an SQL reference constraint Exception (IsSqlReferenceConstraintException ):
Public static bool IsSqlReferenceConstraintException (this Exception occurs t) {var baseEx = Failed T. getBaseException (); if (baseEx is SqlException) {string message = (baseEx as SqlException ). message; if (message. toLower (). contains ("reference constraint") {return true;} else {return false ;}} else if (baseEx! = Null &&! Object. ReferenceEquals (encode T, baseEx) // if the base class is not empty and is not equal to the exception itself, the callback will continue to look for {return IsSqlReferenceConstraintException (baseEx);} return false ;}
Native SQL reports the following error message:
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.
When the extension method is used, the predefined error information is displayed. The call is as follows:
Public void Remove (int userID) {User user = this. repository. Get (t => t. ID = userID); if (User! = Null) {try {this. repository. Remove (user, true);} catch (Exception ex ){If(Ex. IsSqlReferenceConstraintException () // if a reference constraint error is identified, a custom error is thrown.{Throw new Exception ("this account already has other business records associated with it. Deleting is prohibited! If you confirm that this account is not in use, you can disable it. ") ;}} Else {throw new Exception (" this account information does not exist or has been deleted! ");}}