【发布时间】:2022-01-15 03:39:35
【问题描述】:
我有一个 ASP Core 3.1 Web 项目,我想在其中添加 EntityFramework Core。
我创建了一个 db 上下文、具有数据库操作的模型类,并将其注入到我的主类(Azure Bot)中。
但是,当我尝试将记录插入数据库时,它总是失败并显示错误
System.Threading.Tasks.TaskCanceledException: '任务已取消。'
这是我的 startup.cs:
services.AddDbContext<IVRContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
optionBuilder => optionBuilder.EnableRetryOnFailure()
)
);
services.AddTransient<IVRCallModel>();
这是我正在调用的 IVRModel 中的函数:
public async Task InsertCallAsync(IVRCall call)
{
try
{
await _ivrContext.Calls.AddAsync(call);
await _ivrContext.SaveChangesAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
我是这样称呼它的:
private async Task NotificationProcessor_OnNotificationReceivedAsync(NotificationEventArgs args)
{
this.GraphLogger.CorrelationId = args.ScenarioId;
if (args.ResourceData is Call call)
{
if (call.Direction != CallDirection.Outgoing && call.ToneInfo == null)
{
if (args.ChangeType == ChangeType.Created && call.State == CallState.Incoming)
{
await SaveCall(call.Id, call.CallChainId, "Incoming");
.... code removed
}
}
}
}
private async Task SaveCall(string callId, string callChainId, string callState, string redirectCallId = null)
{
IVRCall newCall = new IVRCall();
newCall.Id = callId;
newCall.CallChainId = callChainId;
newCall.TimeStamp = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
newCall.State = callState;
newCall.RedirectCallId = redirectCallId;
await _ivrCallModel.InsertCallAsync(newCall);
}
编辑: “原始” NoticicationProcessor_OnNotificationReceived 函数,它调用异步方法。 (来自 Microsoft 示例项目)
private void NotificationProcessor_OnNotificationReceived(NotificationEventArgs args)
{
_ = NotificationProcessor_OnNotificationReceivedAsync(args).ForgetAndLogExceptionAsync(this.GraphLogger, $"Error processing notification {args.Notification.ResourceUrl} with scenario {args.ScenarioId}");
}
【问题讨论】:
-
throw new Exception(ex.Message, ex);为什么?!您只是无缘无故地在基本Exception类型中包装了一个有意义的异常类型。只需删除try..catch块,让异常正常传播。或者至少重新抛出原来的异常。 -
能分享一下异常的堆栈跟踪吗?
-
System.Threading.Tasks.TaskCanceledException HResult=0x8013153B 消息=任务被取消。 Source=System.Private.CoreLib StackTrace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 这就是它所显示的全部
标签: c# .net-core entity-framework-core