Raise async event in EF's DbContext.SaveChangesAsync()

async-await asynchronous c# entity-framework entity-framework-core

Question

In an ASP.NET Core environment, I'm using EF Core. My context is shown as per-request in my DI container.

I have further work to do before the situation isSaveChanges() or SaveChangesAsync() such as verification, auditing, sending out alerts, etc. That work is split into async and sync portions.

To enable listeners to do more work, I want to raise an async or sync event, block until they are finished (! ), and then call theDbContext real base class to save.

public class MyContext : DbContext
{

  // sync: ------------------------------

  // define sync event handler
  public event EventHandler<EventArgs> SavingChanges;

  // sync save
  public override int SaveChanges(bool acceptAllChangesOnSuccess)
  {
    // raise event for sync handlers to do work BEFORE the save
    var handler = SavingChanges;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // all work done, now save
    return base.SaveChanges(acceptAllChangesOnSuccess);
  }

  // async: ------------------------------

  // define async event handler
  //public event /* ??? */ SavingChangesAsync;

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    // raise event for async handlers to do work BEFORE the save (block until they are done!)
    //await ???
    // all work done, now save
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

}

You can see that it's simple forSaveChanges() but, how do I do it for?SaveChangesAsync() ?

1
2
4/2/2017 12:37:05 PM

Accepted Answer

ZZZ_tmp
2
4/3/2017 2:43:07 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow