我需要从EF的ChangeTracker中的关系中获取属性的值。
我上课了:
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; }
}
要审核日志,请在属性IdTipoCliente上获取TipoClienteInfo的属性Nome
我的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());
}
}
我认为使用属性,关系,但不起作用。
答案 0 :(得分:1)
您可以通过类似的查询从引用(此处为ClienteInfo.TipoCliente
)中获取属性值:
ChangeTracker.Entries<ClienteInfo>()
.Select(e => e.Reference(c => c.TipoCliente)
.TargetEntry.CurrentValues["Nome"])
您的问题尚不清楚,您到底想使用这些值做什么,但这应该可以使您走上正确的轨道。
有几种方法可以更动态地使用它并添加变量/参数,例如:
var referenceName = "TipoCliente";
var propertyName = "Nome";
var values = ChangeTracker.Entries<ClienteInfo>()
.Select(e => e.Reference(referenceName)
.TargetEntry.CurrentValues[propertyName])
.ToList();