コード例 #1
0
        public static IEnumerable <T> GetEntities <T>(this DbChangeTracker tracker)
        {
            var entrySet = tracker.Entries();
            var entities = tracker
                           .Entries()
                           .Where(entry => entry.State != EntityState.Detached && entry.Entity != null)
                           .Select(entry => entry.Entity).OfType <T>();

            return(entities);
        }
コード例 #2
0
ファイル: ChangeTrackingManager.cs プロジェクト: evkap/DVS
		public void BeginTrackChanges(DbChangeTracker changeTracker)
		{
			_changeSet = new ChangeSet()
			{
				ChangeEntities = new List<ChangeEntity>()
			};

			IEnumerable<DbEntityEntry> changes = changeTracker.Entries().Where(e => e.State == EntityState.Deleted || e.State == EntityState.Modified).ToArray();
			AddModifiedEntities(changes);
			_addedEntities = changeTracker.Entries().Where(e => e.State == EntityState.Added).ToArray();
		}
コード例 #3
0
        private static void AntiXssEncode(DbChangeTracker tracker)
        {
            var addedModifiedEntries = tracker.Entries().Where(e => e.State == EntityState.Added | e.State == EntityState.Modified);

            foreach (var entry in addedModifiedEntries)
            {
                var entity     = entry.Entity;
                var type       = entity.GetType();
                var properties = type.GetProperties();

                foreach (var property in properties)
                {
                    if (property.PropertyType != typeof(string))
                    {
                        continue;
                    }

                    var value = property.GetValue(entity, null);

                    if (value == null)
                    {
                        continue;
                    }

                    value = AntiXssEncoder.HtmlEncode(value.ToString(), true);

                    property.SetValue(entity, value, null);
                }
            }
        }
コード例 #4
0
        public void ForEntities(DbChangeTracker tracker)
        {
            var ents = tracker.Entries().Where(te => te.State == EntityState.Added || te.State == EntityState.Modified).ToLookup(te => te.Entity.GetType());

            foreach (var e in ents)
            {
                foreach (var p in e.Key.GetProperties(BindingFlags.DeclaredOnly |
                                                      BindingFlags.Public |
                                                      BindingFlags.Instance).Where(p => p.PropertyType == typeof(string)))
                {
                    foreach (var ent in e)
                    {
                        string val = ent.CurrentValues.GetValue <string>(p.Name);
                        if (val != null)
                        {
                            val = val.Trim();
                            if (val != string.Empty)
                            {
                                val = Sanitizer.Sanitize(val);
                            }
                            ent.CurrentValues[p.Name] = val;
                        }
                    }
                }
            }
        }
コード例 #5
0
        public void ForEntities(DbChangeTracker tracker)
        {
            var ents = tracker.Entries().Where(te => te.State == EntityState.Added || te.State == EntityState.Modified).ToLookup(te => te.Entity.GetType());
            foreach (var e in ents)
            {
                foreach (var p in e.Key.GetProperties(BindingFlags.DeclaredOnly |
                                        BindingFlags.Public |
                                        BindingFlags.Instance).Where(p=>p.PropertyType == typeof(string)))
                {
                    foreach (var ent in e)
                    {
                        string val = ent.CurrentValues.GetValue<string>(p.Name);
                        if (val != null)
                        {
                            val = val.Trim();
                            if (val != string.Empty)
                            {
                                val = Sanitizer.Sanitize(val);
                            }
                            ent.CurrentValues[p.Name] = val;
                        }
                    }
                }

            }
        }
コード例 #6
0
 /// <summary>
 /// Sets the LastUpdatedBy property value to be the logged in user's Id.
 /// </summary>
 /// <param name="tracker">The DbChangeTracker from the DbContext.</param>
 /// <param name="userId">The UserId of the logged in user. This is different than the user that may be in the connection string.</param>
 public static void HandleAuditableLastUpdatedBy(DbChangeTracker tracker, int userId)
 {
     foreach (var auditableEntity in tracker.Entries <IAuditableLastUpdatedBy>().Where(auditableEntity => auditableEntity.State == EntityState.Modified))
     {
         auditableEntity.Entity.LastUpdatedBy = userId;
     }
 }
コード例 #7
0
 /// <summary>
 /// Sets CreateDate to DateTime.Now.
 /// </summary>
 /// <param name="tracker">The DbChangeTracker from the DbContext.</param>
 public static void HandleAuditableCreateDate(DbChangeTracker tracker)
 {
     foreach (var auditableEntity in tracker.Entries <IAuditableCreateDate>().Where(auditableEntity => auditableEntity.State == EntityState.Added))
     {
         auditableEntity.Entity.CreateDate = DateTime.Now;
     }
 }
コード例 #8
0
 /// <summary>
 /// Sets LastUpdated to DateTime.Now.
 /// </summary>
 /// <param name="tracker">The DbChangeTracker from the DbContext.</param>
 public static void HandleAuditableLastUpdated(DbChangeTracker tracker)
 {
     foreach (var auditableEntity in tracker.Entries <IAuditableLastUpdatedDate>().Where(auditableEntity => auditableEntity.State == EntityState.Modified))
     {
         auditableEntity.Entity.LastUpdated = DateTime.Now;
     }
 }
コード例 #9
0
ファイル: DemoDbContext.cs プロジェクト: CodeAperture/HDC2016
        private static void AntiXssEncode(DbChangeTracker tracker)
        {
            var addedModifiedEntries = tracker.Entries().Where(e => e.State == EntityState.Added | e.State == EntityState.Modified);

            foreach (var entry in addedModifiedEntries)
            {
                var entity = entry.Entity;
                var type = entity.GetType();
                var properties = type.GetProperties();

                foreach (var property in properties)
                {
                    if (property.PropertyType != typeof(string))
                    {
                        continue;
                    }

                    var value = property.GetValue(entity, null);

                    if (value == null)
                    {
                        continue;
                    }

                    value = AntiXssEncoder.HtmlEncode(value.ToString(), true);

                    property.SetValue(entity, value, null);
                }
            }
        }
コード例 #10
0
        public static void RejectChanges(this DbChangeTracker changeTracker)
        {
            foreach (var entry in changeTracker.Entries())
            {
                switch (entry.State)
                {
                case EntityState.Modified:
                    entry.State = EntityState.Unchanged;
                    break;

                case EntityState.Added:
                    entry.State = EntityState.Detached;
                    break;

                case EntityState.Detached:
                    break;

                case EntityState.Unchanged:
                    break;

                case EntityState.Deleted:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
コード例 #11
0
        public void ChangeTrackerTest(DbChangeTracker tracker)
        {
            DbChangeTracker changeTracker = this.ChangeTracker;

            System.Data.Entity.Infrastructure.DbChangeTracker fullyQualifiedChangeTracker = this.ChangeTracker;

            var entries = changeTracker.Entries();
        }
コード例 #12
0
        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int                         effected = 0;
                DbChangeTracker             tracker  = entity.ChangeTracker;
                IEnumerable <DbEntityEntry> entries  = tracker.Entries();
                Console.WriteLine(entity.Employees.Count());
                //dataGrid.ItemsSource = entries.ToList();
                if (tracker.HasChanges())
                {
                    IEnumerable <DbEntityEntry> modifiedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Modified);
                    List <Employee>             changes         = new List <Employee>();
                    foreach (DbEntityEntry entityEntry in modifiedEntries)
                    {
                        //DbPropertyValues oldValues = entityEntry.GetDatabaseValues();
                        DbPropertyValues newValues = entityEntry.CurrentValues;
                        Employee         employee  = (Employee)newValues.ToObject();
                        changes.Add(employee);
                    }
                    IEnumerable <DbEntityEntry> deletedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Deleted || n.State == System.Data.Entity.EntityState.Detached);
                    List <Employee>             deletes        = new List <Employee>();
                    foreach (DbEntityEntry entityEntry in deletedEntries)
                    {
                        //DbPropertyValues oldValues = entityEntry.GetDatabaseValues();
                        DbPropertyValues newValues = entityEntry.CurrentValues;
                        Employee         employee  = (Employee)newValues.ToObject();
                        deletes.Add(employee);
                    }
                    IEnumerable <DbEntityEntry> addedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Added);
                    List <Employee>             adds         = new List <Employee>();
                    foreach (DbEntityEntry entityEntry in addedEntries)
                    {
                        //DbPropertyValues oldValues = entityEntry.GetDatabaseValues();
                        DbPropertyValues newValues = entityEntry.CurrentValues;
                        Employee         employee  = (Employee)newValues.ToObject();
                        adds.Add(employee);
                    }
                    ItemChanges itemChanges = new ItemChanges();
                    itemChanges.Topmost = true;
                    itemChanges.dataGridChanges.ItemsSource       = changes.ToList();
                    itemChanges.dataGridChangesDelete.ItemsSource = deletes.ToList();
                    itemChanges.dataGridChangesNew.ItemsSource    = adds.ToList();

                    itemChanges.ShowDialog();
                    if (itemChanges.IsAccepted)
                    {
                        effected = entity.SaveChanges();
                        MessageBox.Show("Success to update data: " + effected.ToString() + " item(s).");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #13
0
 private static void ShowTrackedObjects(string title, DbChangeTracker tracker)
 {
     Console.WriteLine(title);
     foreach (var item in tracker.Entries <Racer>())
     {
         Console.WriteLine("{0}, state: {1}", item.Entity.LastName, item.State);
     }
     Console.WriteLine();
 }
コード例 #14
0
ファイル: Program.cs プロジェクト: L-Henry/FiSo
        private static void DisplayTrackedEntities(DbChangeTracker changeTracker)
        {
            var entries = changeTracker.Entries();

            foreach (var entry in entries)
            {
                Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName);
                Console.WriteLine("Status: {0}", entry.State);
            }
        }
コード例 #15
0
ファイル: ChangeTracking.cs プロジェクト: prasanjeetd/csharp
        public void CheckChangeTracking(DbChangeTracker changeTracker)
        {
            var entries = changeTracker.Entries();

            foreach (var entry in entries)
            {
                var name  = entry.Entity.GetType().FullName;
                var state = entry.State;
            }
        }
コード例 #16
0
 public static string[] GetChangedEntityNames(this DbChangeTracker changeTracker)
 {
     return(changeTracker.Entries()
            .Where(x => x.State == EntityState.Added ||
                   x.State == EntityState.Modified ||
                   x.State == EntityState.Deleted)
            .Select(x => ObjectContext.GetObjectType(x.Entity.GetType()).FullName)
            .Distinct()
            .ToArray());
 }
コード例 #17
0
 public void BeforeSave(DbChangeTracker tracker)
 {
     foreach (var entry in tracker.Entries<ITimestamped>()
         .Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime)))
     {
         var now = DateTime.UtcNow;
         entry.Entity.CreatedAt = now;
         entry.Entity.UpdatedAt = now;
     }
 }
コード例 #18
0
        private static void DisplayTrackedEntities(SchoolDBEntities context)
        {
            Console.WriteLine("Context is tracking {0} entities.", context.ChangeTracker.Entries().Count());
            DbChangeTracker changeTracker = context.ChangeTracker;
            var             entries       = changeTracker.Entries();

            foreach (var entry in entries)
            {
                Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName);
                Console.WriteLine("Status: {0}", entry.State);
            }
        }
コード例 #19
0
        public static void SaveDefaultPropertiesChanges(DbChangeTracker changeTracker)
        {
            foreach (var entry in changeTracker.Entries()
                         .Where(e => e.State == EntityState.Added))
            {
                var exists = entry.Entity.GetType().GetProperty("DataCriacao");

                if (exists != null)
                {
                    entry.Property("DataCriacao").CurrentValue = DateTime.Now;
                }
            }

            foreach (var entry in changeTracker.Entries()
                        .Where(e => e.State == EntityState.Modified))
            {
                var exists = entry.Entity.GetType().GetProperty("DataAlteracao");

                if (exists != null)
                    entry.Property("DataAlteracao").CurrentValue = DateTime.Now;
            }
        }
コード例 #20
0
        /// <summary>
        /// Adds entries to the audit models and returns the RecentUpdateDb. As SaveChanges call is required to commit the changes from the caller.
        /// </summary>
        /// <param name="changeTracker"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public AuditModelContext AuditChanges(DbChangeTracker changeTracker, string userId)
        {
            //Record changes into the Audit DB.
            AuditModelContext recentUpdateDb = new AuditModelContext();

            //Create an exclusion list for audit
            string[] excludedFromAudit = new string[] { "ModifiedById", "Modified", "CreatedById", "Created" };

            IEnumerable <DbEntityEntry> auditEntries = changeTracker.Entries().Where(x => x.Entity is BaseBaseModel && (x.State == EntityState.Modified));


            foreach (DbEntityEntry entry in auditEntries)
            {
                if (entry.GetType().GetCustomAttribute(typeof(NoAuditAttribute)) == null)
                {
                    var currentValues  = entry.CurrentValues;
                    var databaseValues = entry.GetDatabaseValues();

                    if (currentValues != null)
                    {
                        foreach (string propertyName in currentValues.PropertyNames.Except(excludedFromAudit))
                        {
                            if (!string.IsNullOrWhiteSpace(propertyName))
                            {
                                var propertyValue = databaseValues.GetValue <object>(propertyName);

                                //Use nullPlaceholder for equals Operation.
                                object originalValue = propertyValue;
                                object currentValue  = currentValues[propertyName];

                                //Audit changes and non-ReadOnly Fields.
                                if (entry.Entity.GetType().GetProperty(propertyName).GetCustomAttribute(typeof(TFOF.Areas.Core.Attributes.ReadOnlyAttribute)) == null)
                                {
                                    recentUpdateDb.Add(
                                        ObjectContext.GetObjectType(entry.Entity.GetType()).Name,
                                        ((BaseBaseModel)entry.Entity).GetPrimaryKey(),
                                        propertyName,
                                        originalValue,
                                        currentValue,
                                        userId
                                        );
                                }
                            }
                        }
                    }
                }
            }
            return(recentUpdateDb);
        }
コード例 #21
0
        private static void ProcessContextAudit(DbChangeTracker tracker)
        {
            var entriesChangedWithBaseModel = tracker.Entries().Where(e => e.Entity is BaseModel && (e.State == EntityState.Added | e.State == EntityState.Modified));

            foreach (var entry in entriesChangedWithBaseModel)
            {
                var auditEntity = (BaseModel)entry.Entity;
                if (entry.State == EntityState.Added)
                {
                    auditEntity.CreatedOn = DateTime.Now;
                }

                auditEntity.UpdatedOn = DateTime.Now;
            }
        }
コード例 #22
0
        public static void TrackChanges(DbChangeTracker changeTracker)
        {
            foreach (var entry in changeTracker.Entries())
            {
                var entity = (IBaseEntity)entry.Entity;
                switch (entry.State)
                {
                case EntityState.Added:
                    entity.Created = DateTime.Now;
                    entity.Updated = DateTime.Now;
                    break;

                case EntityState.Modified:
                    entity.Updated = DateTime.Now;
                    break;
                }
            }
        }
コード例 #23
0
        private void DisplayTrackedEntities(DbChangeTracker changeTracker)
        {
            Console.WriteLine("");

            var entries = changeTracker.Entries();

            foreach (var entry in entries)
            {
                Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName);
                Console.WriteLine("Status: {0}", entry.State);
                if (entry.State == EntityState.Modified)
                {
                    Console.WriteLine();
                }
            }
            Console.WriteLine("");
            Console.WriteLine("---------------------------------------");
        }
コード例 #24
0
        public static void DisplayTrackedEntities(string label, DbChangeTracker changeTracker)
        {
            Console.WriteLine(label + ":");

            var entries = changeTracker.Entries();

            foreach (var entry in entries)
            {
                Console.WriteLine("Entity Name: {0} [{1}]\tStatus: {2}",
                                  entry.Entity.GetType().FullName, entry.Entity.GetType().Name, entry.State);
                switch (entry.State)
                {
                case System.Data.Entity.EntityState.Added:
                {
                    DisplayDBPropertyValues(entry.CurrentValues, null);
                    break;
                }

                case System.Data.Entity.EntityState.Deleted:
                {
                    DisplayDBPropertyValues(entry.CurrentValues, entry.OriginalValues);
                    break;
                }

                case System.Data.Entity.EntityState.Modified:
                {
                    DisplayDBPropertyValues(entry.CurrentValues, entry.OriginalValues);
                    break;
                }

                case System.Data.Entity.EntityState.Unchanged:
                {
                    // DisplayDBPropertyValues(entry.CurrentValues, entry.OriginalValues);
                    break;
                }

                default:
                {
                    break;
                }
                }
            }
            Console.WriteLine("---------------------------------------");
        }
コード例 #25
0
        private static void DisplayTrackedEntities(DbChangeTracker changeTracker)
        {
            Debug.WriteLine("---------------------------------------------------------------------------------------------------------------------");

            var entries = changeTracker.Entries();

            foreach (var entry in entries)
            {
                Debug.WriteLine($"Entity Name: {entry.Entity.GetType().FullName}");
                Debug.WriteLine($"Status: {entry.State}");

                if (entry.State != EntityState.Detached)//Durumu Detached dışındaki işlemler
                {
                    LiteDbSync(entry);
                }
            }
            Debug.WriteLine("");
            Debug.WriteLine("---------------------------------------------------------------------------------------------------------------------");
        }
コード例 #26
0
        public static void ApplyAuditInformation(this DbChangeTracker changeTracker)
        {
            foreach (var entry in changeTracker.Entries())
            {
                if (!(entry.Entity is BaseEntity baseAudit))
                {
                    continue;
                }

                var now = DateTime.UtcNow;
                switch (entry.State)
                {
                case EntityState.Modified:
                    baseAudit.Created  = now;
                    baseAudit.Modified = now;
                    break;

                case EntityState.Added:
                    baseAudit.Created = now;
                    break;
                }
            }
        }
コード例 #27
0
 public EntityAudit[] Records(DbChangeTracker tracker)
 {
     return(tracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).Select(x => GetRecordsForChange(x)).ToArray());
 }
コード例 #28
0
ファイル: DbChangeTrackerBase.cs プロジェクト: Zedfa/Core
 public IEnumerable <IDbEntityEntryBase> Entries()
 {
     return(_changeTracker.Entries().Select(entry => new DbEntityEntryBase(entry)).AsEnumerable());
 }
コード例 #29
0
        public static TicketHistory GenerateTicketHistory(ApplicationDbContext DbContext, Ticket ticket, ApplicationUser user)
        {
            // Get the props that have been modified, add to new TicketHistory, return it.
            DbChangeTracker changeTracker = DbContext.ChangeTracker;
            var             entries       = changeTracker.Entries();
            var             history       = new TicketHistory();

            history.User = user;

            if (changeTracker.HasChanges())
            {
                var modifiedEntries = (from prop in entries
                                       where prop.State == System.Data.Entity.EntityState.Modified
                                       select prop).FirstOrDefault();

                var historyDetails = (from propName in modifiedEntries.OriginalValues.PropertyNames
                                      let valA = modifiedEntries.OriginalValues[propName]?.ToString()
                                                 let valB = modifiedEntries.CurrentValues[propName]?.ToString()
                                                            where valA != valB && (valA == null || !valA.Equals(valB)) && propName != "DateUpdated"
                                                            select new TicketHistoryDetails()
                {
                    OldValue = valA,
                    NewValue = valB,
                    Property = propName
                }).ToList();

                history.DateUpdated = (from propName in modifiedEntries.OriginalValues.PropertyNames
                                       where propName == "DateUpdated"
                                       select(DateTime) modifiedEntries.CurrentValues[propName]).FirstOrDefault();

                // Converting Ticket status, priority, and types from their id's to more the more user friendly names.
                for (int i = 0; i < historyDetails.Count(); i++)
                {
                    if (historyDetails[i].Property == "TicketStatusId")
                    {
                        var statuses = DbContext.TicketStatuses.ToList();
                        historyDetails[i].Property = "Ticket Status";

                        var parsedIdOld = int.Parse(historyDetails[i].OldValue);
                        historyDetails[i].OldValue = statuses.Find(p => p.Id == parsedIdOld).Name;

                        var parsedIdNew = int.Parse(historyDetails[i].NewValue);
                        historyDetails[i].NewValue = statuses.Find(p => p.Id == parsedIdNew).Name;
                    }
                    else if (historyDetails[i].Property == "TicketPriorityId")
                    {
                        var priorities = DbContext.TicketPriorities.ToList();
                        historyDetails[i].Property = "Ticket Priority";

                        var parsedIdOld = int.Parse(historyDetails[i].OldValue);
                        historyDetails[i].OldValue = priorities.Find(p => p.Id == parsedIdOld).Name;

                        var parsedIdNew = int.Parse(historyDetails[i].NewValue);
                        historyDetails[i].NewValue = priorities.Find(p => p.Id == parsedIdNew).Name;
                    }
                    else if (historyDetails[i].Property == "TicketTypeId")
                    {
                        var types = DbContext.TicketTypes.ToList();
                        historyDetails[i].Property = "Ticket Type";

                        var parsedIdOld = int.Parse(historyDetails[i].OldValue);
                        historyDetails[i].OldValue = types.Find(p => p.Id == parsedIdOld).Name;

                        var parsedIdNew = int.Parse(historyDetails[i].NewValue);
                        historyDetails[i].NewValue = types.Find(p => p.Id == parsedIdNew).Name;
                    }
                    else if (historyDetails[i].Property == "AssignedToId")
                    {
                        var users      = DbContext.Users.ToList();
                        var devUserNew = users.Find(p => p.Id == historyDetails[i].NewValue);
                        var devUserOld = users.Find(p => p.Id == historyDetails[i].OldValue);

                        historyDetails[i].Property = "Dev Assigned";
                        historyDetails[i].OldValue = devUserOld?.DisplayName;
                        historyDetails[i].NewValue = devUserNew?.DisplayName;

                        if (historyDetails[i].OldValue is null)
                        {
                            historyDetails[i].OldValue = "No dev assigned";
                        }
                        if (historyDetails[i].NewValue is null)
                        {
                            historyDetails[i].NewValue = "No dev assigned";
                        }
                    }
                    else if (historyDetails[i].Property == "ProjectId")
                    {
                        var projects = DbContext.Projects.ToList();

                        var devUserNew = projects.Find(p => p.Id.ToString() == historyDetails[i].NewValue);
                        var devUserOld = projects.Find(p => p.Id.ToString() == historyDetails[i].OldValue);

                        historyDetails[i].Property = "Assigned Project";
                        historyDetails[i].OldValue = devUserOld.Title;
                        historyDetails[i].NewValue = devUserNew.Title;
                    }
                }

                foreach (var detail in historyDetails)
                {
                    history.TicketHistoryDetails.Add(detail);
                }
            }

            // Ensures an empty history cannot be created.
            if (history.TicketHistoryDetails.Any())
            {
                return(history);
            }
            else
            {
                return(null);
            }
        }
コード例 #30
0
ファイル: Trailer.cs プロジェクト: anon-070/EF-Trailer
        public override int  SaveChanges()
        {
            if (SaveAudits == false)
            {
                return(base.SaveChanges());
            }


            var addedAuditedEntities = ChangeTracker.Entries()
                                       .Where(p => p.State == EntityState.Added)
                                       .Select(p => p.Entity).ToList();

            var modifiedAuditedEntities = ChangeTracker.Entries()
                                          .Where(p => p.State == EntityState.Modified)
                                          .Select(p => p.Entity).ToList();


            var deletedAuditedEntities = ChangeTracker.Entries()
                                         .Where(p => p.State == EntityState.Deleted)
                                         .Select(p => p.Entity).ToList();

            var unmo = ChangeTracker.Entries()
                       .Where(p => p.State == EntityState.Added).ToList();


            var now = DateTime.UtcNow;

            // Serializer settings
            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.ContractResolver           = new CustomResolver();
            settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            settings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
            settings.Formatting = Formatting.Indented;



            foreach (var modified in modifiedAuditedEntities)
            {
                var      keys      = GetKey(modified, this).Split(',');
                object[] keyvalues = new object[keys.Count()];

                for (int i = 0; i < keys.Count(); i++)
                {
                    keyvalues[i] = modified.GetType().GetProperty(keys[i]).GetValue(modified);
                }

                Trailer asdf = new Trailer();

                var entity2 = asdf.Set(modified.GetType()).Find(keyvalues);



                AuditTrail trail = new AuditTrail()
                {
                    Action         = EntityObjectState.Modified,
                    AuditDateTime  = now,
                    EntityType     = ObjectContext.GetObjectType(modified.GetType()).Name,
                    OriginalEntity = JsonConvert.SerializeObject(entity2, settings),
                    NewEntity      = JsonConvert.SerializeObject(modified, settings),
                    UserId         = (string)User.UserId,
                };

                this.AuditTrails.Add(trail);
            }


            var returnvalue = base.SaveChanges();


            foreach (var added in addedAuditedEntities)
            {
                AuditTrail trail = new AuditTrail()
                {
                    Action         = EntityObjectState.Added,
                    AuditDateTime  = now,
                    EntityType     = added.GetType().Name,
                    OriginalEntity = JsonConvert.SerializeObject(added, settings),
                    UserId         = (string)User.UserId,
                };

                this.AuditTrails.Add(trail);
            }


            foreach (var deleted in deletedAuditedEntities)
            {
                AuditTrail trail = new AuditTrail()
                {
                    Action        = EntityObjectState.Deleted,
                    AuditDateTime = now,
                    EntityType    = ObjectContext.GetObjectType(deleted.GetType()).Name,


                    OriginalEntity = JsonConvert.SerializeObject(deleted, settings),
                    UserId         = (string)User.UserId,
                };

                this.AuditTrails.Add(trail);
            }

            base.SaveChanges();
            return(returnvalue);
        }
コード例 #31
0
ファイル: DemoDbContext.cs プロジェクト: CodeAperture/HDC2016
        private static void ProcessContextAudit(DbChangeTracker tracker)
        {
            var entriesChangedWithBaseModel = tracker.Entries().Where(e => e.Entity is BaseModel && (e.State == EntityState.Added | e.State == EntityState.Modified));

            foreach (var entry in entriesChangedWithBaseModel)
            {
                var auditEntity = (BaseModel) entry.Entity;
                if (entry.State == EntityState.Added)
                {
                    auditEntity.CreatedOn = DateTime.Now;
                }

                auditEntity.UpdatedOn = DateTime.Now;
            }
        }
コード例 #32
0
 public void BeforeSave(DbChangeTracker tracker)
 {
     foreach (var entry in tracker.Entries<ITimestamped>()
         .Where(x => x.State == EntityState.Modified))
         entry.Entity.UpdatedAt = DateTime.Now.ToUniversalTime();
 }