Как получить имя объекта / таблицы и номер записи для добавления аудита? - PullRequest
0 голосов
/ 16 января 2019

Я пытаюсь сделать метод аудита для моей системы, используя EF DbContext.Я перезаписываю событие SaveChanges.Однако у меня есть две трудности, где мне нужна помощь.Я много читал в Интернете и здесь, в StackOverflow, но я все еще не мог найти решение.Вы можете мне помочь?

1) Я не могу получить точное имя таблицы, когда добавляю запись.Когда я добавляю запись в таблицу, просто приходит имя «Объект».Другие операции с именем обычно.

2) После входа в реестр я хотел бы иметь идентификатор реестра для записи в журнал аудита.Любые предложения?

Я ожидаю извинения, если вопросы настолько очевидны, ответы, но я действительно не понимаю, как действовать.

public partial class coletasEntities : DbContext
{
    public override int SaveChanges()
    {
        ChangeTracker.DetectChanges();

        foreach (var change in ChangeTracker.Entries())
        {
            if (change is auditoria || change.State == EntityState.Detached || change.State == EntityState.Unchanged)
                continue;

            //Pega o nome da tabela
            var entityName = change.Entity.GetType().Name;
            //var entityName2 = change.Entity.GetType().BaseType()

            if (entityName == "auditoria") continue;

            // Get the Table() attribute, if one exists
            //TableAttribute tableAttr = change.Entity.GetType().BaseType.Name;
            TableAttribute tableAttr = change.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            //string tableName = tableAttr != null ? tableAttr.Name : ((TableAttribute)tableAttr[0]).Name;
            //string tableName = tableAttr != null ? tableAttr.Name : change.Entity.GetType().Name;
            string tableName = tableAttr != null ? tableAttr.Name : change.Entity.GetType().BaseType.Name;

            // Get primary key value (If you have more than one key column, this will need to be adjusted)
            //string keyName = change.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

            if (change.State == EntityState.Added)
            {
                using (coletasEntities ctx = new coletasEntities())
                {
                    foreach (var prop in change.CurrentValues.PropertyNames)
                    {
                        auditoria audit = new auditoria();

                        audit.campo = prop.ToString();
                        audit.data = DateTime.Now.Date;
                        audit.hora = DateTime.Now.ToShortTimeString();
                        audit.id_registro = 0;
                        audit.id_usuario = Global.id_usuario;
                        audit.tabela = tableName;
                        audit.tipo_operacao = (int)change.State;
                        audit.valor_antigo = "";
                        try
                        {
                            audit.valor_novo = change.CurrentValues[prop].ToString();
                        } catch
                        {
                            audit.valor_novo = "";
                        }

                        ctx.auditoria.Add(audit);
                        ctx.SaveChanges();
                    }
                }
                continue;
            }
            else if (change.State == EntityState.Deleted)
            {
                using (coletasEntities ctx = new coletasEntities())
                {
                    foreach (var prop in change.OriginalValues.PropertyNames)
                    {
                        auditoria audit = new auditoria();

                        audit.campo = prop.ToString();
                        audit.data = DateTime.Now.Date;
                        audit.hora = DateTime.Now.ToShortTimeString();
                        audit.id_registro = 0;
                        audit.id_usuario = Global.id_usuario;
                        audit.tabela = tableName;
                        audit.tipo_operacao = (int)change.State;

                        try
                        {
                            audit.valor_antigo = change.OriginalValues[prop].ToString();
                        }
                        catch
                        {
                            audit.valor_antigo = "";
                        }


                        audit.valor_novo = "";


                        ctx.auditoria.Add(audit);
                        ctx.SaveChanges();
                    }
                }
                continue;
            }
            else if (change.State == EntityState.Modified)
            {
                using (coletasEntities ctx = new coletasEntities())
                {
                    foreach (var prop in change.OriginalValues.PropertyNames)
                    {
                        auditoria audit = new auditoria();

                        audit.campo = prop.ToString();
                        audit.data = DateTime.Now.Date;
                        audit.hora = DateTime.Now.ToShortTimeString();
                        audit.id_registro = 0;
                        audit.id_usuario = Global.id_usuario;
                        audit.tabela = tableName;
                        audit.tipo_operacao = (int)change.State;

                        try
                        {
                            audit.valor_antigo = change.OriginalValues[prop].ToString();
                        }
                        catch
                        {
                            audit.valor_antigo = "";
                        }

                        try
                        {
                            audit.valor_novo = change.CurrentValues[prop].ToString();
                        }
                        catch
                        {
                            audit.valor_novo = "";
                        }

                        if (audit.valor_antigo != audit.valor_novo)
                        {
                            ctx.auditoria.Add(audit);
                            ctx.SaveChanges();
                        }
                    }
                }
                continue;
            }
            else
            {
                // Otherwise, don't do anything, we don't care about Unchanged or Detached entities
            }
        }
        return base.SaveChanges();
    }
}

Любые предложения?

...