これは少し遅いかもしれませんが、詳細を探している ASP.NET データベースの更新エラーを抱えている人にとって、InnerException エラー ハンドラーは非常に役立ち、詳細です。
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 は、重複する都市の挿入を防ぎます。
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
したがって、ユーザーがこのデモ アプリケーションの Addresses テーブルにもう一度「Spokane」を挿入しようとすると、上記の例外ハンドラがレポートします。
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.
使用する例外ハンドラーを知ることは非常に便利であり、質問は非常に明確です。