CleanArchitecture icon indicating copy to clipboard operation
CleanArchitecture copied to clipboard

AuditableEntityInterceptor only processing 'parent' and ignore 'child' entities?

Open mrhighstone opened this issue 10 months ago • 5 comments

Is it correct that the AuditableEntityInterceptor only processes 'parent' entities and ignore 'child' entities?

I'm having a parent-child relation in my application, lets say an Order holding OrderLineItems. After adding items to the list and saving the Order, the AuditableEntityInterceptor correctly updates the created and updated properties of the Order but ignores the OrderLineItems.

Is this as intended? And if so, how to also update the auditable fields of an OrderLineItem when the Order is saved?

mrhighstone avatar Feb 27 '25 08:02 mrhighstone

Is your OrderLineItem class also inheriting from BaseAuditableEntity? And are they being tracked by the DbContext?

DennisJansenDev avatar Feb 27 '25 09:02 DennisJansenDev

Yes, it is inheriting from BaseAuditableEntity.

But it is clearly not being tracked by the DbContext. It is created in the database, however.

Effectively, all that that command handler is doing, after fetching the Order and instantiating the OrderLineItem is

order.OrderLineItems.Add(lineItem)

Followed by

 _context.SaveChangesAsync();

And I was hoping this was enough to get the job done, and not having the command handler thinking about entities being tracked or not.

mrhighstone avatar Feb 27 '25 09:02 mrhighstone

Hi @mrhighstone If your child entities are not being tracked, you might need to explicitly detect changes: "AutoDetectChangesEnabled" _context.ChangeTracker.DetectChanges(); //_context.savechangeasync();

VipulHanda avatar Mar 11 '25 05:03 VipulHanda

Thanks for the reply @VipulHanda but unfortunately this won't work. It's SaveChanges that actually triggers the AuditableEntityInterceptor.

mrhighstone avatar Mar 26 '25 19:03 mrhighstone

Never mind, I resolved the issue. I had the AuditableEntityInterceptor been executed before the DispatchDomainEventsInterceptor was. And the child entries were in fact added in an event. Obviously, the AuditableEntityInterceptor wasn't aware of any entries being added after the auditing was executed.

Note to self, first dispatch domain events ;-)

services.AddScoped<ISaveChangesInterceptor, DispatchDomainEventsInterceptor>();        
services.AddScoped<ISaveChangesInterceptor, AuditableEntityInterceptor>();

mrhighstone avatar Mar 26 '25 20:03 mrhighstone