Entity Framework: How to properly handle exceptions that occur due to SQL constraints

巧了我就是萌 提交于 2019-11-28 21:22:24

You should be able to trap the SQL error number (which is SqlException.Number)

In this case it's 2627 which has been the same forever for SQL Server.

If you want abstraction, then you'll always have some dependency on the database engine because each one will throw different exception numbers and messages.

One way is to inspect the Errors property of the inner SqlException. The SqlError class has a Number property that identifies the exact error. See the master.dbo.sysmessages table for a list of all error codes.

Of course this still ties you to Sql Server. I'm not aware of a way to abstract this away other than roll your own 'EF exception analyzer'.

This scenario should not happen as the key should never be assign explicitly when using EF; rather allowing the context to assign an appropriate one. If its a concurrency issue then you should do the update in a transaction scope.

Then if you have an UpdateException you could retry the update again. You can safely do that in a transaction scope and only complete the scope when the update goes thorough. In this scenario the chances of the update going through the next time is greater than the first one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!