Exemple #1
0
        public IEnumerable <Audit> GetEntityHistory(IAuditEntity e)
        {
            var name = e.GetType().FullName;

            var tables = _appDbContext.Set <Table>();
            var table  = tables.FirstOrDefault(o => o.Name == name);

            if (table == null)
            {
                return(null);
            }

            var auditTable = _appDbContext.Set <Audit>();

            return(auditTable.Where(o => o.EntityId == e.Id && o.TableId == table.Id).ToList());
        }
        private IAuditEntity AuditEntity(DbEntityEntry entityEntry, AuditTypeInfo auditTypeInfo, DateTimeOffset auditDateTime, string user)
        {
            // Create audit entity.
            DbSet        set         = this.Set(auditTypeInfo.AuditEntityType);
            IAuditEntity auditEntity = set.Create() as IAuditEntity;

            // Check audit entity for complex types.
            var complexTypes = GetComplexTypes(auditTypeInfo, entityEntry);

            //Instantiate complex types.
            foreach (var field in complexTypes)
            {
                var property   = auditEntity.GetType().GetProperty(field);
                var entityType = property.PropertyType;
                property.SetValue(auditEntity, Activator.CreateInstance(entityType));
            }

            //Attach audit Entity to the context.
            set.Add(auditEntity);

            // Copy the properties.
            DbEntityEntry auditEntityEntry = this.Entry(auditEntity);

            foreach (string propertyName in auditTypeInfo.AuditProperties)
            {
                auditEntityEntry.Property(propertyName).CurrentValue = entityEntry.Property(propertyName).OriginalValue;
            }

            // Set the audit columns.
            auditEntityEntry.Property(AuditUpdatedColumnName).CurrentValue  = auditDateTime;
            auditEntityEntry.Property(AuditUserColumnName).CurrentValue     = user;
            auditEntityEntry.Property(AuditTypeColumnName).CurrentValue     = entityEntry.State == EntityState.Modified ? "update" : "delete";
            auditEntityEntry.Property(AuditSourceIdColumnName).CurrentValue = entityEntry.OriginalValues.GetValue <int>("Id");

            return(auditEntity);
        }