简体   繁体   中英

Override SaveChangesAsync

Does anyone know how to override SaveChangesAsync? I know a similar question was posted but there was no answer. I have the following code below:

public override async Task<int> SaveChangesAsync()
{
    PerformFurtherValidations();
    return await base.SaveChangesAsync();
}

During Build I get the following error message:

Error SaveChangesAsync(): return type must be System.Threading.Tasks.Task<int> to match overridden member System.Data.Entity.DbContext.SaveChangesAsync()

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
    return (await base.SaveChangesAsync(true, cancellationToken));
}

Old question, but I had a similar problem and resolved it with the following code:

    public override async Task<int> SaveChangesAsync()
    {
        foreach (var history in this.ChangeTracker.Entries()
            .Where(e => e.Entity is IModificationHistory && (e.State == EntityState.Added ||
                e.State == EntityState.Modified))
            .Select(e => e.Entity as IModificationHistory)
            )
        {
            history.DateModified = DateTime.Now;
            if (history.DateCreated <= DateTime.MinValue)
            {
                history.DateCreated = DateTime.Now;
            }
        }
        int result = await base.SaveChangesAsync();
        foreach (var history in this.ChangeTracker.Entries()
                                        .Where(e => e.Entity is IModificationHistory)
                                        .Select(e => e.Entity as IModificationHistory))
        {
            history.IsDirty = false;
        }
        return  result;
    }

The custom SaveChangesAsync() allows me to tweak the dirty flag, date created and date modified.

It's better to return the task to the caller, you don't need to call an async method inside your version of SaveChanges, just omit "await" and "async" keywords:

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
    PerformFurtherValidations();
    return base.SaveChangesAsync();
}

I faced the same issue and the root cause was that the EntityFramework reference to the project was from

\packages\EntityFramework.6.3.0\lib.net40

folder instead of

\packages\EntityFramework.6.3.0\lib.net45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM