EntityFrameworkCore.Triggered icon indicating copy to clipboard operation
EntityFrameworkCore.Triggered copied to clipboard

Trigger Event On Sub Entity Save

Open Alchemy86 opened this issue 3 years ago • 2 comments

Apologies if I'm being slow with this or I'm failing to find the documentation for it.

I have existing system, large and complex. I have used this before for smaller things but here I'm trying to remove existing records from a repo when a new record is added. As they can be added in unknown numbers of places, I'm using the library to trigger a clear before save on this Entity.

BUT. It seems a number of records are being added as a sub entity of another object. These end up in the DB without triggering the .. trigger.

Is there a way to configure the trigger to also fire if it is a sub entity of another record? Or can it not detect this. Or worse, should it already be working and for me its not.

Thanks,

Alchemy86 avatar Jun 09 '22 15:06 Alchemy86

Hi @Alchemy86

Triggers will only fire for entities that are in a Added/Modified/Deleted state.

a number of records are being added as a sub entity of another object

Then all triggers targeting the entity type that is being added will be raised.

Is there a way to configure the trigger to also fire if it is a sub entity of another record?

Yes, by implementing a trigger that targets the sub entity type.

record Parent(int Id, List<Child> Children);
record Child(int Id);

class ParentTrigger : IBeforeSaveTrigger<Parent> { ... }
class ChildTrigger : IBeforeSaveTrigger<Child> { ... }

var parent = new Parent(0, new());
dbContext.Add(parent);
dbContext.SaveChanges(); // Will raise ParentTrigger

var child = new Child(0);
dbContext.Add(child);
dbContext.SaveChanges(); // Will raise ChildTrigger

parent.Children.Add(child);
dbContext.SaveChanges(); // Will raise ChildTrigger as the ForeignKey is configured on the Child

Let me know if this helps

koenbeuk avatar Jun 09 '22 17:06 koenbeuk

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Aug 09 '22 06:08 stale[bot]