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.
SQL error codes are stored in the Master.sys.messages table
After the breakpoint tracking exception, it is concluded that the number of the exception is corresponding to the message_id here,
Therefore, we can write the extension method:
Extend exception to determine whether exception is a SQL Reference constraint exception method (Issqlreferenceconstraintexception):
/// <summary> ///See if a constraint conflict/// </summary> /// <param name= "Exception" ></param> /// <returns></returns> Public Static BOOLIssqlreferenceconstraintexception ( ThisException Exception) { varBaseex =exception. GetBaseException (); if(Baseex isSqlException) { if((Baseex asSqlException). Number = =547) { return true; } Else { return false; } } Else if(Baseex! =NULL&&!Object. ReferenceEquals (Exception, Baseex))//if the base class is not empty and does not equal the exception itself, proceed back to the investigation to find { returnissqlreferenceconstraintexception (Baseex); } return false; }
The calling code is as follows:
Try{base_module C=NewBase_module () {RowID =RowID}; Entities. Entry (c). State=System.Data.EntityState.Deleted; Entities. SaveChanges (); returngzapisuccess (); } Catch(Dbupdateexception ex) {if(true==Ex. Issqlreferenceconstraintexception ()) {returnGzapibadrequest ("Delete failed with associated data", Enumresponsecode.errsqlreferenceconstraintexception, Sqloot.delete); } Else Throwex; }
Reference: https://www.cnblogs.com/zuowj/p/4414031.html
Reference: http://www.cnblogs.com/liuzhixian/p/3839787.html
Extend exception to determine if exception is a SQL Reference constraint exception Method!