Entity Framework Core Triggers In Action (Unofficial Package)

This article shows you how to work with database triggers in  Entity Framework Core using a third party library.

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:  I have 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 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 using Entity Framework Core or Entity Framework 6+. For the demo, I have used Entity Framework Core with ASP.NET Core. 

Below is how I used the package to easily solve my problem. Install the package via Nuget with the following command,

  1. Install-Package EntityFrameworkCore.Triggers  

Here are the entities used for the demo.

  1. public class Inventory  
  2. {  
  3.     public int Id { get; set; }  
  4.     public string Moniker { get; set; }  
  5.   
  6.     public List<InventoryItem> InventoryItems { get; set; }  
  7. }  
  8.   
  9. public class Item  
  10. {  
  11.     public int Id { get; set; }  
  12.     public decimal CostPerUnit { get; set; }  
  13.     public int CurrentQuantity { get; set; } = 0;  
  14.     public List<InventoryItem> InventoryItems { get; set; }  
  15. }  
  16.   
  17. public class InventoryItem  
  18. {  
  19.     public int Id { get; set; }  
  20.     public int IssuedQuantity { get; set; }  
  21.   
  22.     public int ItemId { get; set; }  
  23.     public Item Item { get; set; }  
  24.   
  25.     public int InventoryId { get; set; }  
  26.     public Inventory Inventory { get; set; }  
  27. }   

I have used those entities to declare DbSet<T> in the ApplicationDbContext file.

  1. public class ApplicationDbContext : DbContext  
  2. {  
  3.     public DbSet<Item> Items { get; set; }  
  4.     public DbSet<Inventory> Inventories { get; set; }  
  5.     public DbSet<InventoryItem> InventoryItemRelation { get; set; }  
  6. }   

I used MVC scaffolding for generating Controllers and their respective Views for these entities. I won’t show the code for them here. Please download the repository to have a better look at those.

The next thing to do is to create Insert and Delete triggers for updating the value of CurrentQuantityfield respective to the value of IssuedQuantity field.

Here go the triggers in the overridden SaveChangesAsync method of ApplicationDbContext.

  1. public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,   
  2.          CancellationToken cancellationToken = default(CancellationToken))  
  3. {  
  4.     Triggers<InventoryItem>.Inserting +=   
  5.              entry => entry.Entity.Item.CurrentQuantity += entry.Entity.IssuedQuantity;  
  6.     Triggers<InventoryItem>.Deleting += entry =>   
  7.              entry.Entity.Item.CurrentQuantity -= entry.Entity.IssuedQuantity;  
  8.   
  9.     return this.SaveChangesWithTriggersAsync(base.SaveChangesAsync,   
  10.              acceptAllChangesOnSuccess: true, cancellationToken: cancellationToken);  
  11. }   

Everything will work smoothly now. If you update the 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 triggers for the sake of simplicity but you have the Update trigger also for use if you want.

Don’t forget calling the SaveChangesWithTriggersAsync in your SaveChangesAsync method. Otherwise, the triggers won’t get registered.

By the way, you have to modify the Create and Delete action generated by the default scaffolding engine for InventoryItem entity like the following 

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<IActionResult>   
  4.     Create([Bind("Id,IssuedQuantity,ItemId,InventoryId")] InventoryItem inventoryItem)  
  5. {  
  6.     if (ModelState.IsValid)  
  7.     {  
  8.         var item = _context.Items.Find(inventoryItem.ItemId);  
  9.         var inventory = _context.Inventories.Find(inventoryItem.InventoryId);  
  10.   
  11.         inventoryItem.Item = item;  
  12.         inventoryItem.Inventory = inventory;  
  13.   
  14.         _context.Add(inventoryItem);  
  15.         await _context.SaveChangesAsync();  
  16.         return RedirectToAction("Index");  
  17.     }  
  18.     ViewData["InventoryId"] =   
  19.        new SelectList(_context.Inventories, "Id""Id", inventoryItem.InventoryId);  
  20.     ViewData["ItemId"] = new SelectList(_context.Items, "Id""Id", inventoryItem.ItemId);  
  21.     return View(inventoryItem);  
  22. }  
  23.   
  24. // POST: InventoryItems/Delete/5  
  25. [HttpPost, ActionName("Delete")]  
  26. [ValidateAntiForgeryToken]  
  27. public async Task<IActionResult> DeleteConfirmed(int id)  
  28. {  
  29.     var inventoryItem = await _context.InventoryItemRelation.SingleOrDefaultAsync(m => m.Id == id);  
  30.   
  31.     var item = _context.Items.Find(inventoryItem.ItemId);  
  32.     var inventory = _context.Inventories.Find(inventoryItem.InventoryId);  
  33.   
  34.     inventoryItem.Item = item;  
  35.     inventoryItem.Inventory = inventory;  
  36.   
  37.     _context.InventoryItemRelation.Remove(inventoryItem);  
  38.     await _context.SaveChangesAsync();  
  39.     return RedirectToAction("Index");  
  40.  

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

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

  • https://github.com/NickStrupat/EntityFramework.Triggers

Up Next
    Ebook Download
    View all
    Learn
    View all