我正在尝试在MVC项目上实现审计跟踪,通过添加另一个功能来覆盖上下文(以便审计)。 SaveChanges的重写工作正常,但我遇到的问题是SaveChangesAsync。 以下是上下文中代码的一部分
public override Task<int> SaveChangesAsync()
{
throw new InvalidOperationException("User ID must be provided");
}
public override int SaveChanges()
{
throw new InvalidOperationException("User ID must be provided");
}
public async Task<int> SaveChangesAsync(int userId)
{
DecidSaveChanges(userId);
return await this.SaveChangesAsync(CancellationToken.None);
}
public int SaveChanges(int userId)
{
DecidSaveChanges(userId);
return base.SaveChanges();
}
我遇到的问题是我的控制器
await db.SaveChangesAsync(1);
1是虚拟用户。我收到以下错误。
Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.
你知道我在做错了什么吗?以及如何解决它?我正在使用EF6和MVC5
答案 0 :(得分:5)
你知道我在这里做错了吗?
是的,只需查看编译器错误消息:
The 'await' operator can only be used within an async method.
因此,控制器操作(包含对SaveChangesAsync(1)
的调用)必须为async
。
以及如何修复它?
是的,只需查看编译器错误消息:
Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.
因此,您可以通过控制器操作async
并将其返回类型从ActionResult
更改为Task<ActionResult>
来解决此问题。