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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top