Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

like image 607
DannyT Avatar asked Sep 23 '14 17:09

DannyT


1 Answers

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.

like image 165
pStan Avatar answered Sep 17 '22 21:09

pStan