1
Hello, I’m starting to work with Efcore and I’m doing an Override on the method SaveChanges()
so that whenever there is a manipulation of the bank I can log this manipulation. My problem is that I am working with Schemas in my bank and do not know how to capture the same of a EntityEntry
. My code is 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 can I know which Entity Schema I am working on?
thank you very much Kra, I am "beginner" in csharp and even more with Efcore, helped me a lot!
– LeandroLuk