我正在使用Entity Framework并尝试调用存储过程,但ExecuteSqlCommandAsync
正在抛出未处理的异常。我已经把try / catch但是代码没有进入catch块。 ExecuteSqlCommand
方法运行正常。
我得到的例外是
System.NullReferenceException'发生在mscorlib.dll
我的代码:
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)
{
}
有谁知道代码可能出现什么问题?
答案 0 :(得分:0)
通过使用ExecuteSqlCommandAsync(),代码在另一个线程中运行,并且异常不在您的控制范围内。可以在AppDomain.CurrentDomain.UnhandledException事件处理程序中全局处理未处理的异常。该异常处理程序只是防止应用程序崩溃,而不能用于解决您的问题。仅供参考。
要解决您的问题,请使用另一种方法,创建自己的异步任务,以便您可以完全控制异常。并将您的异步呼叫替换为相应的同步呼叫。
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)
{
}
});
}