Entity Framework Core Triggers in Action (Unofficial Package)

10 July 2017

Recently I have had this problem of updating a field of an entity that is dependent on another field of another entity. Confused already? Let me give you an example: so, I've these Inventory and Item entities where there exists a many-to-many relation between them. So, of course there should also be a relation table between them i.e. InventoryItem. The problem I was having actually is I have had this one field called CurrentQuantity on the Item entity and other called IssuedQuantity on the relation table (InventoryItem). Thus, as you might have already guessed that I've had to somehow update the CurrentQuantity field of the Item entity based on the IssuedQuantity field of the InventoryItem entity.

And now for the solution: my path crossed with this beautiful package named EntityFrameworkCore.Triggers created by Nick Strupat. Using this package, you can enable support for Triggers in your project that is using Entity Framework Core or Entity Framework 6+. For the demo, I have used Entity Framework Core with ASP.NET Core.

Everything will work smoothly now. If you update value of the IssuedQuantity field while managing relation between Item and Inventory it will also update the CurrentQuantity field. Here, I'm only listening for the Insert and Delete trigger for the sake of simplicity but you have the Update trigger also for use if you want.

Nothing fancy here, just got the appropriate Item and Inventory references using the InventoryId and ItemId fields available inside the inventoryItem parameter. Then attached the references back to the inventoryItem parameter again so that we don't get any null reference errors.

I've covered very basics here. To know more about the package and other available configurations, refer to this github repository. It is open source yay!