Entity Framework Code First and SQL Server 2012 Sequences

前端 未结 1 1995
攒了一身酷
攒了一身酷 2021-01-06 18:43

I was in the middle of implementing a database audit trail whereby CRUD operations performed through my controllers in my Web API project would serialize the old and new poc

1条回答
  •  孤城傲影
    2021-01-06 19:08

    Don't know if this might help you, but this is how I did my audit log trail using code first. The following is coded into a class inheriting from DbContext.

    in my constructor I have the following

    IObjectContextAdapter objectContextAdapter = (this as IObjectContextAdapter);
    objectContextAdapter.ObjectContext.SavingChanges += SavingChanges;
    

    This is my saving changes method wired up previously

    void SavingChanges(object sender, EventArgs e) {
            Debug.Assert(sender != null, "Sender can't be null");
            Debug.Assert(sender is ObjectContext, "Sender not instance of ObjectContext");
    
            ObjectContext context = (sender as ObjectContext);
            IEnumerable modifiedEntities = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
            IEnumerable addedEntities = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
    
            addedEntities.ToList().ForEach(a => {
                //Assign ids to objects that don't have
                if (a.Entity is IIdentity && (a.Entity as IIdentity).Id == Guid.Empty)
                    (a.Entity as IIdentity).Id = Guid.NewGuid();
    
                this.Set().Add(AuditLogEntryFactory(a, _AddedEntry));
            });
    
            modifiedEntities.ToList().ForEach(m => {
                this.Set().Add(AuditLogEntryFactory(m, _ModifiedEntry));
            });
        }
    

    And these are the methods used previosly to build up the audit log details

    private AuditLogEntry AuditLogEntryFactory(ObjectStateEntry entry, string entryType) {
            AuditLogEntry auditLogEntry = new AuditLogEntry() {
                EntryDate = DateTime.Now,
                EntryType = entryType,
                Id = Guid.NewGuid(),
                NewValues = AuditLogEntryNewValues(entry),
                Table = entry.EntitySet.Name,
                UserId = _UserId
            };
    
            if (entryType == _ModifiedEntry) auditLogEntry.OriginalValues = AuditLogEntryOriginalValues(entry);
    
            return auditLogEntry;
        }
    
        /// 
        /// Creates a string of all modified properties for an entity.
        /// 
        private string AuditLogEntryOriginalValues(ObjectStateEntry entry) {
            StringBuilder stringBuilder = new StringBuilder();
    
            entry.GetModifiedProperties().ToList().ForEach(m => {
                stringBuilder.Append(String.Format("{0} = {1},", m, entry.OriginalValues[m]));
            });
    
            return stringBuilder.ToString();
        }
    
        /// 
        /// Creates a string of all modified properties' new values for an entity.
        /// 
        private string AuditLogEntryNewValues(ObjectStateEntry entry) {
            StringBuilder stringBuilder = new StringBuilder();
    
            for (int i = 0; i < entry.CurrentValues.FieldCount; i++) {
                stringBuilder.Append(String.Format("{0} = {1},",
                    entry.CurrentValues.GetName(i), entry.CurrentValues.GetValue(i)));
            }
    
            return stringBuilder.ToString();
        }
    

    Hopefully this might point you into a direction that might help you solve your problem.

    0 讨论(0)
提交回复
热议问题