覆盖 SaveChangesAsync

override SaveChangesAsync

我正在尝试通过添加另一项功能(以进行审计)来覆盖上下文,从而在 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

do you know what I am doing wrong here?

是的,看看你的编译器错误信息:

The 'await' operator can only be used within an async method.

因此,控制器操作(包含对 SaveChangesAsync(1) 的调用)需要 async

and how to fix it?

是的,看看你的编译器错误信息:

Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.

因此,您通过使控制器动作 async 并将其 return 类型从 ActionResult 更改为 Task<ActionResult> 来修复它。