How to handle unique constraint exception in datatable while adding record in C#

后端 未结 2 1196
小鲜肉
小鲜肉 2021-01-28 16:20

I have added unique constraint to datatable like this

DataTable dtemp
private void TempTable() 
{
 dtemp = new DataTable(\"Temp\");
 dtemp.Columns.Add(new DataCo         


        
相关标签:
2条回答
  • 2021-01-28 16:45

    This is not a SQLException. Change your handling to be more specific around the exception. If you can't resolve that - change it to a regular Exception.

    private void GetTable()
        {
            try
            { 
                dtemp.Rows.Add(mTable.TableID,mTable.Capacity);
            }
            catch(Exception ee)
            {                
                MessageBox.Show("Exception: " + ee.Message);
            } 
    

    I would avoid using exceptions in this scenario. This is really a bad pattern. It is especially painful to debug when you have all exceptions turned on. A better practice is to check if the record exists, then add if it doesn't.

    Think of exceptions as edge cases for unexpected events - not regular coding practices.

    0 讨论(0)
  • 2021-01-28 16:59

    Since you have define your constraint in the local DataTable, you're trying to catch the wrong type of exception. Instead of SqlException, a ConstraintException is thrown.

    An immediate fix would be, to change the type of exception in your try clause:

    try
    { 
        dtemp.Rows.Add(mTable.TableID,mTable.Capacity); 
    } 
    catch (ConstraintException ee) 
    {
        // handle the exception here 
    }
    

    If you want to check your constraint in the database, then that's where you want to define it instead of in the DataTable. In this case, SqlException will get thrown, but only when you send the data to the database, not when you add a row to the DataTable.

    0 讨论(0)
提交回复
热议问题