Entity Framework override SaveChanges() on Service layer instead of Data layer (different projects)

asp.net asp.net-web-api entity-framework entity-framework-6

Question

My ASP.NET WebAPI application has Data & Service layer, multiple projects in one solution.

Data Layer (Entity Framework)
-DbContext.cs

Service Layer (Business Logic)
-Controller.cs
-Global.asax

One of my entities requires business logic intercept every time it run DbContext SaveChanges().

public class MyDbContext : DbContext
{

    public override int SaveChanges()
    {
        BusinessLogicAndUpdateEntity(); //Code from Service Layer
        return base.SaveChanges();
    }
}

Currently the business logic resides in service layer, and data project can't reference service layer project else the project will be circular referencing each other.

Is there a way for me to override DbContext SaveChanges() in service layer without moving my business logic to the data layer?

1
0
8/26/2018 12:31:54 PM

Accepted Answer

You could fire an event in MyDbContext (maybe it already exists in DbContext?)

public delegate void BeforeSaveChangesSignature ();
public class MyDbContext : DbContext
{
    public event BeforeSaveChangesSignature BeforeSaveChanges {get; set;}

    public override int SaveChanges()
    {
        BeforeSaveChanges?.Invoke(); 
        return base.SaveChanges();
    }
}

Your business logic would then subscribe the event, and performing whatever they need:

...
var context = new MyDbContext();
context.BeforeSaveChanges  += () => { Console.WriteLine("Before save"); }
...
2
8/25/2018 2:33:00 PM


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