如何获得实体/表的名称和添加审核的记录号?

时间:2019-01-16 19:02:26

标签: c# entity-framework audit

我正在尝试使用EF DbContext对系统进行审核。我覆盖了SaveChanges事件。但是,在需要帮助的地方我有两个困难。我已经在Internet上和StackOverflow上阅读了很多东西,但是仍然找不到解决方案。你能帮我吗?

1)添加记录时,我无法获得表的实际名称。当我将记录添加到表中时,只需输入名称“ Object”即可。其他名称正常的操作。

2)输入注册表后,我希望将注册表ID放入审核日志中。有什么建议吗?

如果问题的答案很明显,我希望道歉,但我真的不知道如何进行。

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();
    }
}

有没有建议?

1 个答案:

答案 0 :(得分:0)

使用此 auditEntry.TableName = entry.Metadata.Relational()。TableName; 以下是一个示例:

       foreach (var entry in ChangeTracker.Entries())
        {
            if (entry.Entity is Audit || entry.State == EntityState.Detached || 
            entry.State == EntityState.Unchanged)
                continue;

            var auditEntry = new AuditEntry(entry);
            auditEntry.TableName = entry.Metadata.Relational().TableName;
            auditEntries.Add(auditEntry);

            foreach (var property in entry.Properties)
            {
                if (property.IsTemporary)
                {

                    auditEntry.TemporaryProperties.Add(property);
                    continue;
                }

                string propertyName = property.Metadata.Name;
                if (property.Metadata.IsPrimaryKey())
                {
                    auditEntry.KeyValues[propertyName] = property.CurrentValue;
                    continue;
                }

                switch (entry.State)
                {
                    case EntityState.Added:
                        auditEntry.NewValues[propertyName] = property.CurrentValue;
                        break;

                    case EntityState.Deleted:
                        auditEntry.OldValues[propertyName] = property.OriginalValue;
                        break;

                    case EntityState.Modified:
                        if (property.IsModified)
                        {
                            auditEntry.OldValues[propertyName] = property.OriginalValue;
                            auditEntry.NewValues[propertyName] = property.CurrentValue;
                        }
                        break;
                }
            }
        }