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?





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




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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?