Reputation: 576
I am using Entity Framework and trying to call a stored procedure, but ExecuteSqlCommandAsync
is is throwing an unhandled exception. I have put try/catch but code is not going into the catch block. ExecuteSqlCommand
method works fine.
The exception I am getting is
System.NullReferenceException' occurred in mscorlib.dll
My code:
try
{
var inboundsParam = new SqlParameter();
inboundsParam.ParameterName = "@Inbounds";
inboundsParam.SqlDbType = SqlDbType.Xml;
inboundsParam.Direction = ParameterDirection.Input;
inboundsParam.Value = inboundsXml;
var incomeFoundOutParam = new SqlParameter();
incomeFoundOutParam.ParameterName = "@IncomeFound";
incomeFoundOutParam.SqlDbType = SqlDbType.Bit;
incomeFoundOutParam.Direction = ParameterDirection.Output;
var output = await dbContext.Database.ExecuteSqlCommandAsync("EXEC dbo.CalculateIncome @Inbounds, @IncomeFound OUTPUT", inboundsParam, incomeFoundOutParam);
var incomeFound = (bool)incomeFoundOutParam.Value;
}
catch(System.Exception ex)
{
}
Does anyone know what could be wrong with the code?
Upvotes: 0
Views: 1090
Reputation: 201
By using ExecuteSqlCommandAsync(), the code is running in another thread, and Exceptions are out of your control. Unhandled exceptions can be globally handled in AppDomain.CurrentDomain.UnhandledException event handler. This exception handler just keep your application from crash, but should not be used to solve your problem. This is just for your information.
To solve your problem, use an alternative way, create your own async tasks, so that you have the full control of exceptions. And replace your async call with the corresponding sync call.
public async void YourMethodAsync()
{
// NOTE HERE TO CREATE YOUR OWN TASK, SO THAT YOU HAVE CONTROL TO THE EXCEPTION
Task.Run(()=>{
try
{
var inboundsParam = new SqlParameter();
inboundsParam.ParameterName = "@Inbounds";
inboundsParam.SqlDbType = SqlDbType.Xml;
inboundsParam.Direction = ParameterDirection.Input;
inboundsParam.Value = inboundsXml;
var incomeFoundOutParam = new SqlParameter();
incomeFoundOutParam.ParameterName = "@IncomeFound";
incomeFoundOutParam.SqlDbType = SqlDbType.Bit;
incomeFoundOutParam.Direction = ParameterDirection.Output;
// NOTE HERE, USE SYNC METHOD CALL.
var output = dbContext.Database.ExecuteSqlCommand("EXEC dbo.CalculateIncome @Inbounds, @IncomeFound OUTPUT", inboundsParam, incomeFoundOutParam);
var incomeFound = (bool)incomeFoundOutParam.Value;
}
catch(System.Exception ex)
{
}
});
}
Upvotes: 1