why Is my Update method not letting me get Current and Original entity values on SaveChangesAsnyc override?

57 Views Asked by At

I have the following update method to update all fields of a record:

public async Task<TUsers> Update<T>(T updatedRecord, string operatorId) where T : BaseUser
{
    var operator = await MyContext.TUsers.FirstOrDefaultAsync(u => u.userId == operatorId);
    if (operator == null) throw new BusinessException("Action denied");

    TUsers oldRecord = await SearchUser(updatedRecord.Id);
    if (fichaAntiga == null) throw new BusinessException("User not found");

    updatedRecord.UpdatedOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF");
    updatedRecord.UpdatedBy = operator.Id;

    MyContext.Entry(oldRecord).CurrentValues.SetValues(updatedRecord);

    await MyContext.SaveChangesAsync();

    return new TUsers();
}

I've overrided the SaveChangesAsync method on MyContext to get the old record and the new one and log them on a MongoDB collection. But the problem is that both of the properties shows the new record. Here's my override

 public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    {
        var modifiedEntities = ChangeTracker.Entries()
            .Where(p => p.State == EntityState.Modified).ToList();

        foreach (var change in modifiedEntities)
        {
            Console.WriteLine(change.OriginalValues);
            Console.WriteLine(change.CurrentValues);
        }

        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }

I put a breakpoint on the beginning of the method and inspect the values inside change.OriginalValues.InternalEntry.Entity and change.CurrentValues.InternalEntry.Entity and they both have the same values, including its navigation properties.

0

There are 0 best solutions below