I need handle exception duplicate.
var resource = new Reso开发者_C百科urce() { 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.
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.
See AppDomain.CurrentDomain.UnhandledException. Also, for WPF application is make sense to look at the Application.Current.DispatcherUnhandledException
the best practice is to write the exception message and stack trace to 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/
精彩评论