EF Core - ChangeTracker.DetectChanges get value from specific property

audit-trail entity-framework-core logging

Question

I need to get the value of a property from a relationship in EF's ChangeTracker.

I have the class:

public class ClienteInfo
{
    public Guid Id { get; set; }
    public Guid IdTipoCliente { get; set; }
    public string Nome { get; set; }
    public bool Ativo { get; set; }
    public bool Bloqueado { get; set; }

    public virtual TipoClienteInfo TipoCliente { get; set; }
}

public class TipoClienteInfo
{
     public Guid Id { get; set; }
     public string Nome { get; set; }
     public bool Ativo { get; set; }

     public virtual ICollection<ClienteInfo> Clientes { get; set; }
}

To Audit Log, on property IdTipoCliente get property Nome of TipoClienteInfo

My ContextClass:

public class DataBaseContext : DbContext
{
    public DbSet<ClienteInfo> Cliente { get; set; }
    public DbSet<TipoClienteInfo> TipoCliente { get; set; }


    public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
    {
        ChangeTracker.DetectChanges();

        foreach (var entry in ChangeTracker.Entries())
        {
            foreach (var property in entry.Properties)
            {
                //GET HERE THE VALUE
            }
        }

        var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        return result;
    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        RegisterMaps(modelBuilder);
    }

    public static void RegisterMaps(ModelBuilder builder)
    {
        builder.ApplyConfiguration(new ClienteMaps());
        builder.ApplyConfiguration(new TipoClienteMaps());
    }
}

I think use attribute, relfection, but not working.

1
0
4/24/2019 4:59:26 PM

Accepted Answer

You can get property values from references (here: ClienteInfo.TipoCliente) by a query like this:

ChangeTracker.Entries<ClienteInfo>()
    .Select(e => e.Reference(c => c.TipoCliente)
                  .TargetEntry.CurrentValues["Nome"])

It's not clear from your question what exactly you want to do with these values but this should get you on the right track.

There are several ways to use this more dynamically and add variables/parameters, for example:

var referenceName = "TipoCliente";
var propertyName = "Nome";

var values = ChangeTracker.Entries<ClienteInfo>()
                  .Select(e => e.Reference(referenceName)
                                .TargetEntry.CurrentValues[propertyName])
                  .ToList();
1
4/25/2019 9:57:51 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow