SaveChanges()
method so that whenever there is a manipulation of the database I can log it. My problem is that I'm working with Schemas in my bank and I do not know how to capture the same as a EntityEntry
. My code looks like this:
public partial class MyContext : DbContext
{
// construtores...
// models
// ...
public int SaveChanges(int userId)
{
var snapshots = ChangeTracker.Entries().ToList();
var now = DateTime.UtcNow;
foreach (var s in snapshots)
{
var entityName = s.Entity.GetType().Name;
var schemaName = ""; // como pego isso aqui ?
var primaryKey = getKey(s);
var actionName = s.State.ToString();
var obj = new Dictionary<string, string>();
var props = s.OriginalValues.Properties
.Select(x=> x.Name).ToList();
foreach (var prop in props)
{
var originalValue = s.OriginalValues[prop].ToString();
var currentValue = s.CurrentValues[prop].ToString();
if (originalValue != currentValue)
obj.Add(prop, currentValue.ToString());
}
Log log = new Log()
{
Acao = $"({actionName}) {schemaName}.{entityName}",
Registro = JsonConvert.SerializeObject(obj)
};
Log.Add(log);
}
return base.SaveChanges();
}
public override int SaveChanges()
{
return SaveChanges(0);
}
public virtual int getKey(EntityEntry entity)
{
var keyName = Model.FindEntityType(entity.GetType())
.FindPrimaryKey().Properties
.Select(x => x.Name).Single();
return (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
}
All my models are structured as in the example below:
[Table("Foo", Schema = "Bar")]
public partial class Foo
{
// ...
}
How do I know which Entity Schema I am working on?