我使用实体框架来访问我的SQL数据。我在数据库模式中有一些约束,我想知道如何处理由这些约束引起的异常。
例如,当两个用户试图同时向DB添加一个(几乎)相同的实体时,我得到了以下异常。
System.Data.UpdateException
"An error occurred while updating the entries. See the InnerException for details."
(inner exception) System.Data.SqlClient.SqlException
"Violation of UNIQUE KEY constraint 'Unique_GiftId'. Cannot insert duplicate key in object 'dbo.Donations'.\r\nThe statement has been terminated."
如何正确地捕获此特定异常?
Dirty解决方案:
catch (UpdateException ex)
{
SqlException innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Message.StartsWith("Violation of UNIQUE KEY constraint 'Unique_GiftId'"))
{
// handle exception here..
}
else
{
throw;
}
}
现在,虽然这种方法有效,但它也有一些缺点:
上唯一抽象的名称
你知道更好的解决方案吗?感谢您的所有反馈..
注意:我不想在应用层中手动编写约束代码,我希望将它们放在数据库中。
https://stackoverflow.com/questions/3694359
复制相似问题