2010-03-08 7 views

risposta

39

assume che si sta utilizzando SQL Server.

Utilizzando teh Googles - http://blogs.msdn.com/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx

try 
{ 
    # SQL Stuff 
} 
catch (SqlException ex) 
{ 
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error 
    { 
     switch (ex.Errors[0].Number) 
     { 
      case 547: // Foreign Key violation 
       throw new InvalidOperationException("Some helpful description", ex); 
       break; 
      case 2601: // Primary key violation 
       throw new DuplicateRecordException("Some other helpful description", ex); 
       break; 
      default: 
       throw new DataAccessException(ex); 
     } 
    } 

} 

caso 547 è il vostro uomo.

UPDATE Quanto sopra è un codice di esempio e non deve essere utilizzato. Si prega di seguire il link per spiegare perché.

+2

Se segui il collegamento e leggi, noterai che il codice sopra riportato è un esempio di come * not * non lo fa ... – bornfromanegg

+0

Assolutamente corretto: avevo solo intenzione di avere questo codice qui per mostrare una versione espansa della cattura degli errori. Suppongo che dovrei mettere un avviso da non usare (poiché questo è il problema con l'altra pagina). – aronchick

-2

scrivi tu codice di eccezione del previsto nel blocco try eventuale eccezione verrà generata sarà cattura ulteriormente ora è possibile ottenere errore number.now può verificare è un Esteri violazione di chiave o no

try 
{ 

//your deletetion code 

}catch (SqlException ex) 
    { 

     if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error 
     { 
      switch (ex.Errors[0].Number) 
      { 
       case 547: // Foreign Key violation 
        lblError.Text = "Cannot Delete this Record this is associated with other record...!"; 

        break; 
       default: 
        throw; 

      } 
     } 
    } 
+1

Si prega di non ripetere altre risposte –

Problemi correlati