Search code examples
sql-serverentity-frameworkstored-procedureslinq-to-entities

Entity Framework does not catch SQL Exception


I am using stored procedures and running the stored procedures using "FromSql" feature provided by Microsoft Entity framework Core.

When there is a SQL exception Entity Framework does not catch the exception at all.

For example below, the stored procedure "GetAppSections" is missing in SQL.When I run the app In the debug mode I can locate the "missing stored proc" error deep inside the local window.

However logic never goes to the "Catch" block.Entity Framework simply runs the 'FromSql' command and returns an empty object. The "catch" block is never hit.

Any idea why Entity Framework is not catching the "missing stored proc" exception from SQL?

 public virtual IEnumerable<appSection> GetSections()
    {
        try
        {

            return _context.appSections.FromSql("dbo.GetAppSections @p0",
                                     parameters: new[] { _standarParams.userID.ToString()}).AsEnumerable();

        }
        catch (Exception ex)
        {
           // error handling code
        }
    }

Solution

  • You are returning an IEnumerable which is deferred. You need the try catch block around the code that actually accesses that IEnumerable (ToList, ForEach, etc).

    See here and here