Using Entity Framework and Raw SQL for stored procedures and exception handling

c# entity-framework-core

Question

I can successfully use stored procedures using ExecuteSqlRawAsync or FromSqlRaw in EF but I want to be able to catch exceptions in case the stored procedure returns an error using ERROR_SEVERITY().

For example I have an insert statement in a stored procedure and I am using a Try Catch in the procedure. In the catch I use,

SELECT 
    ERROR_SEVERITY() AS ErrorSeverity, 
    ERROR_PROCEDURE() AS ErrorProcedure,
    ERROR_MESSAGE() AS ErrorMessage;

In C# I use ExecuteSqlRawAsync to execute the procedure and if there is a SQL error I don't get the Severity code since there is no return value in ExecuteSqlRawAsync. Do I need to use FromSqlRaw to get the returned value even for an insert?

I want to catch the exception on the C# side.

1
0
4/9/2020 3:14:32 PM

Popular Answer

Jeroen's solution is correct. I removed the error handling from the stored procedure and of course I now get an SqlException in my C# code which is want I wanted to see.

0
4/9/2020 4:37:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow