Entity Framework override SaveChanges() on Service layer instead of Data layer (different projects)
Entity Framework override SaveChanges() on Service layer instead of Data layer (different projects)
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 Answer
1
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");
...
thanks for the solution. Is that possible to attach the event globally? as many classes are using MyDbContext that created locally.
– JR Tan
Aug 25 at 14:42
@JRTan I would recommend using a factory to create instances of MyDbContext. It could be tempting to use ´static´ to solve this, but be carefull. ´static´and events are a dangerous mix :)
– Jens Kloster
Aug 25 at 18:23
I wouldn't recommend such a "wormhole", see my comment above.
– Gert Arnold
Aug 25 at 18:50
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I think the controller should be the middleman here. DAL shoudn't notify BL. The controller should notify both.
– Gert Arnold
Aug 25 at 18:49