'How to update aggregate root datetime in ef core

I need to update aggregate root ModifiedOn in EF core, what I've done is I override SaveChangesAsync and find those entities that have updates in changetracker.

  • Api
        var employee=await _employeeRepository.GetEmployeeById(employeeId);
        employee.UpdateTimesheet(timeSheetId, description);
        await _employeeRepository.SaveChanges();
        return employee;

and in SaveChangesAsync I call HandleTracker method to update datetime:

private void HandleTracker()
    {
        var entries = ChangeTracker
            .Entries()
            .Where( e => e.Entity is ITimeAudit &&
                         ( e.State == EntityState.Added || e.State == EntityState.Modified ) );
        foreach ( var entityEntry in entries.Where( x => x.Entity is ITimeAudit ) ) {
            var entity = (ITimeAudit) entityEntry.Entity;
            switch ( entityEntry.State ) {
                case EntityState.Detached:
                    break;
                case EntityState.Unchanged:
                    break;
                case EntityState.Deleted:
                    break;
                case EntityState.Added:
                    entity.CreatedOn  = DateTime.UtcNow;
                    entity.ModifiedOn = DateTime.UtcNow;
                    break;
                case EntityState.Modified:
                    entity.ModifiedOn = DateTime.UtcNow;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

in this case only TimeSheet modifiedOn will be updated.

Solution:

One solution is to inform changetracker that Employee entity is also has been updated by following code:

_dbContext.Entry(employee).State = EntityState.Modified;

Need another solution if available: Is there any solotion without informing changetracker to update the employee modified on?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source