覆盖SaveChangesAsync

chr*_*ris 1 model-view-controller entity-framework

我试图在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();
    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我的控制器

    await db.SaveChangesAsync(1);
Run Code Online (Sandbox Code Playgroud)

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>'.   
Run Code Online (Sandbox Code Playgroud)

你知道我在做错了什么吗?以及如何解决它?我正在使用EF6和MVC5

Ste*_*ary 5

你知道我在做错了什么吗?

是的,只需查看编译器错误消息:

The 'await' operator can only be used within an async method.
Run Code Online (Sandbox Code Playgroud)

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

以及如何解决它?

是的,只需查看编译器错误消息:

Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过执行控制器操作async并将其返回类型更改为ActionResult来修复它Task<ActionResult>.