Search code examples
c#entity-framework-4updateexception

How handle UpdateException?


I need handle exception duplicate.

var resource = new Resource() { url = tbUrl.Text };
try
{
    context.Resource.AddObject(resource);
    context.SaveChanges();
}   
catch(UpdateException ex)
{
    // how to know exactly which is why the error occurred
}
catch (Exception ex)
{

    throw;
}

UPDATE:

I need to catch an error that occurs when I try to not add unique value. UpdateException - is triggered when an error in adding data.


Solution

  • This may be a little late, but for anyone with an ASP.NET database update error looking for details, the InnerException error handler is extraordinary helpful and detailed.

            try { 
    
                db.SaveChanges();                              
            }
    
            catch (System.Data.UpdateException ex)    
            {
                Console.WriteLine(ex.InnerException);
            }
    
    
            catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
            {
                Console.WriteLine(ex.InnerException);
            }
    
            catch (Exception ex)
            {
    
                Console.WriteLine(ex.InnerException);
                throw;
            }
    

    The T-SQL in the database prevents the insertion of duplicate cities.

    USE [ModelFirstApplication]
    GO
    
    /****** Object:  Index [UQ_Address_City]    Script Date: 5/30/2012 7:26:16 AM ******/
    ALTER TABLE [dbo].[Addresses] ADD  CONSTRAINT [UQ_Address_City] UNIQUE NONCLUSTERED 
    ([City] ASC)
    GO
    

    So, if the user tries inserting "Spokane" a second time into the Addresses table into this demo application, the above exception handler reports

    System.Data.UpdateException: An error occurred while updating the entries. 
    
    See the inner exception for details. ---> 
    
    System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'UQ_Address_City'. 
    Cannot insert duplicate key in object 'dbo.Addresses'. 
    The duplicate key value is (Spokane).
    The statement has been terminated.
    

    Knowing which exception handler to use is pretty darned handy and your question is quite clear.