How to handle UpdateException?

I need to handle duplicate exceptions.

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 the error that occurs when I try not to add a unique value . UpdateException - throws when an error occurs when adding data.

+4
source share
3 answers

It may be a bit late, but for those who have an ASP.NET database update error, to find the details, the InnerException error handler is extremely useful 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; } 

T-SQL in the database prevents the insertion of duplicated 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 to insert "Spokane" a second time into the address table in 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 of the exception handlers to use is pretty good, and your question is clear enough.

+5
source

it is best to write an exception message and a stack trace to the log file and get the data by reading the log file i reccomand using log4net http://sadi02.wordpress.com/2008/06/29/log4net-tutorial-in-c-net- how-can-i-show-log-in-a-file /

0
source

See AppDomain.CurrentDomain.UnhandledException . Also, for a WPF application, it makes sense to take a look at Application.Current.DispatcherUnhandledException

0
source

All Articles