Adding entity to DBcontext in SyncObjectsStatePreCommit

Jun 12, 2014 at 6:50 PM
How can I add an entity to the context just before calling savechanges() ?

In my Models I have an AuditHistory Model. In the SyncObjectsStatePreCommit() function I want to add a new AuditHistory object to the context and then Call SaveChanges(), so that the Entity (being actually persisted) and the AuditHistory entity are both saved together.

Thanks in advance.
Jun 19, 2014 at 5:58 PM
Got it to work: Please see below how I added a AuditHistory table to the system.
Now before any operation I created an Audit History object and attached to the the context before Saving the Operation Entity + Audit History object to the DB.
  1. Create AuditHistory table in your DB
  2. Generate POCO
  3. Create interface IAdutHistory
  4. Register dependencies
  5. Update SyncObjectsStatePreCommit as shown below.
// your context class will now have something like
public DbSet<AuditHistory> AuditHistories { get; set; }

// in model project
public partial class AuditHistory : Infrastructure.DataAccess.Entity, Infrastructure.Interfaces.IAuditHistory, Infrastructure.IObjectState
{
    public System.Guid AuditHistoryId { get; set; }
    public System.Guid RecordId { get; set; }
    public string TableName { get; set; }
    public string UserId { get; set; }
    public string Actions { get; set; }
    public string OldData { get; set; }
    public string NewData { get; set; }

    [NotMapped]
    public ObjectState ObjectState { get; set; }

    public System.DateTime CreatedDatetime { get; set; }
    public System.Guid CreatedBy { get; set; }
    public System.DateTime ModifiedDatetime { get; set; }
    public System.Guid ModifiedBy { get; set; }
}
// in interface
public interface IAuditHistory : IObjectState
{
    System.Guid AuditHistoryId { get; set; }
    System.Guid RecordId { get; set; }
    string TableName { get; set; }
    string UserId { get; set; }
    string Actions { get; set; }
    string OldData { get; set; }
    string NewData { get; set; }

    System.DateTime CreatedDatetime { get; set; }
    System.Guid CreatedBy { get; set; }
    System.DateTime ModifiedDatetime { get; set; }
    System.Guid ModifiedBy { get; set; }
}
// register dependency
container.RegisterType<IAuditHistory, Models.AuditHistory>();

// in DataContext
private void SyncObjectsStatePreCommit()
    {
        // update created and modified properties
        foreach (var dbEntityEntry in this.ChangeTracker.Entries())
        {

            dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);

            switch(dbEntityEntry.State)
            {
                case (EntityState.Added):
                    {
                        ((Entity)dbEntityEntry.Entity).CreatedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).CreatedBy = new Guid("some guid");
                        ((Entity)dbEntityEntry.Entity).ModifiedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).ModifiedBy = new Guid("some guid");
                        ((IObjectContextAdapter)this).ObjectContext.AddObject("AuditHistories", GetAuditHistory(dbEntityEntry));            
                        break;
                    }
                case (EntityState.Modified):
                    {
                        ((Entity)dbEntityEntry.Entity).ModifiedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).ModifiedBy = new Guid("some guid");
                        dbEntityEntry.OriginalValues.SetValues(dbEntityEntry.GetDatabaseValues());
                        ((IObjectContextAdapter)this).ObjectContext.AddObject("AuditHistories", GetAuditHistory(dbEntityEntry));

                        break;
                    }
                case (EntityState.Deleted):
                    {
                        break;
                    }
            }
        }
    }


    public IAuditHistory GetAuditHistory(DbEntityEntry entry)
    {
        IUnityContainer container = CoreUnitContainer.GetUnityContainer();
        var oAuditLog =  container.Resolve<IAuditHistory>();
        oAuditLog.AuditHistoryId = Guid.NewGuid();
        oAuditLog.TableName = ((Entity)entry.Entity).GetType().ToString();
        oAuditLog.RecordId = GetKeyValue(entry);
        oAuditLog.UserId = "shaq2676";
        oAuditLog.Actions = entry.State.ToString();
        oAuditLog.CreatedBy = ((Entity)entry.Entity).CreatedBy;
        oAuditLog.CreatedDatetime = ((Entity)entry.Entity).CreatedDatetime;

        ((IAuditHistory)oAuditLog).ObjectState = ObjectState.Added;

        //entry is Added 
        if (entry.State == EntityState.Added)
        {
            var newValues = new StringBuilder();
            SetAddedProperties(entry, newValues);
            oAuditLog.NewData = newValues.ToString();
            oAuditLog.Actions = ObjectState.Added.ToString();
            oAuditLog.ModifiedBy = oAuditLog.CreatedBy;
            oAuditLog.ModifiedDatetime = oAuditLog.CreatedDatetime;
        }
        //entry in deleted
        else if (entry.State == EntityState.Deleted)
        {
            var oldValues = new StringBuilder();
            SetDeletedProperties(entry, oldValues);
            oAuditLog.OldData = oldValues.ToString();
            oAuditLog.Actions = ObjectState.Deleted.ToString();
            oAuditLog.ModifiedBy = ((Entity)entry.Entity).ModifiedBy;
            oAuditLog.ModifiedDatetime = ((Entity)entry.Entity).ModifiedDatetime;
        }
        //entry is modified
        else if (entry.State == EntityState.Modified)
        {
            var oldValues = new StringBuilder();
            var newValues = new StringBuilder();
            SetModifiedProperties(entry, oldValues, newValues);
            oAuditLog.OldData = oldValues.ToString();
            oAuditLog.NewData = newValues.ToString();
            oAuditLog.Actions = ObjectState.Modified.ToString();
            oAuditLog.ModifiedBy = ((Entity)entry.Entity).ModifiedBy;
            oAuditLog.ModifiedDatetime = ((Entity)entry.Entity).ModifiedDatetime;
        }

        return oAuditLog;
    }
Marked as answer by shaq2676 on 6/19/2014 at 10:59 AM