Is it possible to retrieve SQL error codes from unsuccessful entity framework data operations?

血红的双手。 提交于 2019-12-13 02:25:23

问题


SQL returns codes that are preceded by a minus sign (-) indicate that the SQL statement execution was unsuccessful. (All SQL defined error codes are negative integers).

In previous applications, I have used a stored procedure based SQL data layer that checks for these error codes and translates them into user friendly error messages which are then displayed to the end user.

I have been testing the validity of replacing the old stored procedure based system for a system based around the Entity Framework. The only problem that I have come across so far is that I can't find any way to retrieve the SQL error codes that explain any database related operation failures. After extensive searching online and finding nothing, I figured that someone here has to know the answer.

So my simple question is... is there any way that I can access the SQL error codes from each SQL statement execution when using the Entity Framework?

Many thanks in advance.


回答1:


Yes you can catch the SqlException wich has detailed informations about your exception.

try
{
   // do your changes
   myDbContext.SaveChanges();
}
catch (SqlException ex)
{
    // ex.LineNumber
    // ex.ErrorCode
    foreach (SqlError error in ex.Errors)
    {
        // error.LineNumber
    }
}

More informations about SqlException Class

hope this helps



来源:https://stackoverflow.com/questions/8340711/is-it-possible-to-retrieve-sql-error-codes-from-unsuccessful-entity-framework-da

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