Exemplo n.º 1
0
        /// <summary>
        /// 获取数据上下文的变更日志信息
        /// </summary>
        public static IEnumerable <DataLog> GetEntityDataLogs(this DbContext dbContext, IServiceProvider provider)
        {
            if (provider == null)
            {
                return(Enumerable.Empty <DataLog>());
            }
            IEntityInfoHandler entityInfoHandler = provider.GetService <IEntityInfoHandler>();

            if (entityInfoHandler == null)
            {
                return(Enumerable.Empty <DataLog>());
            }

            ObjectContext      objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
            ObjectStateManager manager       = objectContext.ObjectStateManager;

            IEnumerable <DataLog> logs = from entry in manager.GetObjectStateEntries(EntityState.Added).Where(entry => entry.Entity != null)
                                         let entityInfo = entityInfoHandler.GetEntityInfo(entry.Entity.GetType())
                                                          where entityInfo != null && entityInfo.DataLogEnabled
                                                          select GetAddedLog(entry, entityInfo);

            logs = logs.Concat(from entry in manager.GetObjectStateEntries(EntityState.Modified).Where(entry => entry.Entity != null)
                               let entityInfo = entityInfoHandler.GetEntityInfo(entry.Entity.GetType())
                                                where entityInfo != null && entityInfo.DataLogEnabled
                                                select GetModifiedLog(entry, entityInfo));

            logs = logs.Concat(from entry in manager.GetObjectStateEntries(EntityState.Deleted).Where(entry => entry.Entity != null)
                               let entityInfo = entityInfoHandler.GetEntityInfo(entry.Entity.GetType())
                                                where entityInfo != null && entityInfo.DataLogEnabled
                                                select GetDeletedLog(entry, entityInfo));

            return(logs);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Private extension method for ObjectStateManager class
        /// Dump all tracking info to a string
        /// </summary>
        /// <param name="manager">ObjectStateManager</param>
        /// <param name="objectStateEntries">Collection of ObjectStateEntries. If null, then all entities will be displayed</param>
        /// <param name="entityKey">EntityKey of given entity. If null, then all entities will be displayed</param>
        /// <param name="asHtml">Output string as HTML</param>
        /// <returns>String with tracking info about entries</returns>
        private static string Dump(this ObjectStateManager manager, IEnumerable <ObjectStateEntry> objectStateEntries, EntityKey entityKey, bool asHtml)
        {
            var dump = new StringBuilder();

            if (entityKey != null)
            {
                objectStateEntries = new List <ObjectStateEntry>();
                (objectStateEntries as List <ObjectStateEntry>).Add(manager.GetObjectStateEntry(entityKey));
            }
            else if (objectStateEntries == null)
            {
                objectStateEntries =
                    manager.GetObjectStateEntries(EntityState.Added)
                    .Union(manager.GetObjectStateEntries(EntityState.Modified))
                    .Union(manager.GetObjectStateEntries(EntityState.Deleted))
                    .Union(manager.GetObjectStateEntries(EntityState.Unchanged));
            }

            dump.AppendFormat("ObjectStateManager entries : # {0}\n", objectStateEntries.Count());

            foreach (var entry in objectStateEntries)
            {
                dump.Append(ObjectStateEntryToString(entry));

                if (entry.State == EntityState.Added)
                {
                    for (var i = 0; i < entry.CurrentValues.FieldCount; i++)
                    {
                        dump.AppendFormat("\n\t- {0} = {1}",
                                          entry.CurrentValues.GetName(i),
                                          ObjectToString(entry.CurrentValues[i]));
                    }
                }
                else if (entry.State == EntityState.Modified)
                {
                    foreach (var prop in entry.GetModifiedProperties())
                    {
                        dump.AppendFormat("\n\t- {0} : {1} -> {2}",
                                          prop,
                                          ObjectToString(entry.OriginalValues[prop]),
                                          ObjectToString(entry.CurrentValues[prop]));
                    }
                }
            }

            if (asHtml)
            {
                dump.Replace("\n", "<br />");
                dump.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            else
            {
                dump.Replace("<b>", "");
                dump.Replace("</b>", "");
            }

            return(dump.ToString());
        }
Exemplo n.º 3
0
        public void RefreshAllModifiedObjects(bool ignoreExceptions = true)
        {
            IEnumerable <ObjectStateEntry> objectStates =
                ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

            Refresh(RefreshMode.StoreWins, objectStates.Where(item => !item.IsRelationship).Select(item => item.Entity));
        }
Exemplo n.º 4
0
        public override int SaveChanges(System.Data.Objects.SaveOptions options)
        {
            foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
            {
                dynamic e = entry.Entity;

                if (entry.State == EntityState.Added)
                {
                    try
                    {
                        e.CreatedDate = DateTime.Now;
                        e.CreatedBy   = OAMSSetting.Username;
                    }
                    catch (Exception)
                    {
                    }
                }

                try
                {
                    e.LastUpdatedDate = DateTime.Now;
                    e.LastUpdatedBy   = OAMSSetting.Username;
                }
                catch (Exception)
                {
                }



                // Validate the objects in the Added and Modified state
                // if the validation fails throw an exeption.
            }
            return(base.SaveChanges(options));
        }
        public IEnumerable <T> ManagedEntities <T>()
        {
            var oses = ObjectStateManager.GetObjectStateEntries();

            return(oses.Where(entry => entry.Entity is T)
                   .Select(entry => (T)entry.Entity));
        }
Exemplo n.º 6
0
        public override int SaveChanges(SaveOptions options)
        {
            try
            {
                var now = DateTime.UtcNow;

                var entities = ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                               .Select(e => e.Entity)
                               .OfType <IHasEntryTimeStamp>();

                foreach (var entry in entities)
                {
                    // IHasEntryTimeStamp lastModified = entry as IHasEntryTimeStamp;
                    //if (lastModified != null)
                    entry.EntryTimeStamp = now;
                }

                return(base.SaveChanges(options));
            }
            catch (UpdateException u)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// откатывам все изменения в контексте,
        /// </summary>
        public void Rollback()
        {
            ServerAction = true;
            //detaching all added entities
            var addedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added);

            foreach (var objectStateEntry in addedEntities)
            {
                Detach(objectStateEntry.Entity);
            }
            var deletedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);

            //apply origin value for all modified entities
            foreach (var objectStateEntry in deletedEntities)
            {
                if (objectStateEntry.Entity != null)
                {
                    ObjectStateManager.ChangeObjectState(objectStateEntry.Entity, EntityState.Modified);
                }
            }

            //apply origin value for all modified entities
            var modifiedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

            foreach (var objectStateEntry in modifiedEntities)
            {
                RevertEntityScalars((EntityObject)objectStateEntry.Entity);
            }

            //set state for every changed entities in unchanged
            AcceptAllChanges();
            ServerAction = false;
        }
Exemplo n.º 8
0
        /// <summary>
        /// универсальный *перегруженный метод
        /// </summary>
        public new bool SaveChanges()
        {
            try {
                IEnumerable <ObjectStateEntry> addedEntities   = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
                IEnumerable <ObjectStateEntry> deletedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);

                ServerAction = true;
                ((ObjectContext)this).SaveChanges();
                addedEntities.ToList();
                deletedEntities.ToList();
                addedEntities   = null;
                deletedEntities = null;
                ServerAction    = false;

                if (SavedChanges != null)
                {
                    SavedChanges(this, null);
                }
                return(true);
            } catch (UpdateException e) {
                Exception showException = e.InnerException ?? e;
                LoggerContext.Instance.AddError(showException);

                if (ShowError)
                {
                    MessageBox.Show(showException.Message);
                }
                LastError = showException;

                Rollback();

                return(false);
            }
        }
Exemplo n.º 9
0
        public new int SaveChanges()
        {
            foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added))
            {
                Type targetType = entry.Entity.GetType();

                PropertyInfo[] pInfoList;

                if (Dict.ContainsKey(targetType))
                {
                    pInfoList = Dict[targetType];
                }
                else
                {
                    pInfoList = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                }
                foreach (PropertyInfo pInfo in pInfoList)
                {
                    if (pInfo.Name.Equals("InsertDate") || pInfo.Name.Equals("UpdateDate") || pInfo.Name.Equals("AccessDate") || pInfo.Name.Equals("RegistDate") || pInfo.Name.Equals("RegisterDateTime"))
                    {
                        pInfo.SetValue(entry.Entity, CurrentInfoHolder.GetBoundDateTime(), null);
                    }
                    else if (pInfo.Name.Equals("InsertUser") || pInfo.Name.Equals("UpdateUser") || pInfo.Name.Equals("RegisterSystem"))
                    {
                        pInfo.SetValue(entry.Entity, CurrentInfoHolder.GetBoundUser(), null);
                    }
                    else if (pInfo.Name.Equals("VersionNo") || pInfo.Name.Equals("Version"))
                    {
                        pInfo.SetValue(entry.Entity, 1, null);
                    }
                }
            }

            return(base.SaveChanges());
        }
Exemplo n.º 10
0
        private void SavingChangesHandler(object sender, EventArgs e)
        {
            var errorBuilder = new StringBuilder();

            foreach (var entry in ObjectStateManager.GetObjectStateEntries(
                         EntityState.Added | EntityState.Modified))
            {
                var entity = entry.Entity as IDataErrorInfo;
                if (entity != null)
                {
                    string error = entity.Validate();
                    if (!string.IsNullOrEmpty(error))
                    {
                        //errorBuilder.AppendInNewLine(string.Format(CultureInfo.CurrentCulture, Resources.EntityInvalid,
                        //    EntityToString(entity), error));
                        Debug.Assert(false);
                    }
                }
            }

            string errorMessage = errorBuilder.ToString();

            if (!string.IsNullOrEmpty(errorMessage))
            {
                throw new ValidationException(errorMessage);
            }
        }
Exemplo n.º 11
0
        public void CommitAndRefreshChanges()
        {
            try
            {
                Commit();
            }
            catch (OptimisticConcurrencyException ex)
            {
                //if client wins refresh data ( queries database and adapt original values
                //and re-save changes in client
                Refresh(RefreshMode.ClientWins, ex.StateEntries.Select(se => se.Entity));

                SaveChanges();

                //accept all changes in STE entities attached in context
                var steEntities = (from entry in
                                   ObjectStateManager.GetObjectStateEntries(~EntityState.Detached)
                                   where
                                   entry.Entity != null
                                   &&
                                   (entry.Entity as IObjectWithChangeTracker != null)
                                   select
                                   entry.Entity as IObjectWithChangeTracker);

                steEntities.ToList().ForEach(ste => ste.MarkAsUnchanged());
            }
        }
Exemplo n.º 12
0
 public override int SaveChanges(SaveOptions options)
 {
     foreach (ObjectStateEntry relationEntry in ObjectStateManager
              .GetObjectStateEntries(EntityState.Deleted)
              .Where(e => e.IsRelationship))
     {
         var entry = GetEntityEntryFromRelation(relationEntry, 0);
         // Find representation of the relation
         IRelatedEnd relatedEnd = entry.RelationshipManager
                                  .GetAllRelatedEnds()
                                  .First(r => r.RelationshipSet == relationEntry.EntitySet);
         RelationshipType relationshipType = relatedEnd.RelationshipSet.ElementType;
         if (!SkipDeletion(relationshipType))
         {
             // Now we know that model is inconsistent and entity on many side must be deleted
             if (!(relatedEnd is EntityReference))     // related end is many side
             {
                 entry = GetEntityEntryFromRelation(relationEntry, 1);
             }
             if (entry.State != EntityState.Deleted)
             {
                 context.DeleteObject(entry.Entity);
             }
         }
     }
     return(base.SaveChanges());
 }
Exemplo n.º 13
0
        public void RollbackChanges()
        {
            IEnumerable <object> itemsToRefresh = ObjectStateManager.GetObjectStateEntries(EntityState.Modified)
                                                  .Where(ose => !ose.IsRelationship && ose.Entity != null)
                                                  .Select(ose => ose.Entity);

            Refresh(RefreshMode.StoreWins, itemsToRefresh);
        }
Exemplo n.º 14
0
        public void GetChanges(ObjectStateManager Entities)
        {
            var entries = Entities.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted);

            foreach (var Item in entries)
            {
            }
        }
Exemplo n.º 15
0
        public void OnSavingChanges(object sender, System.EventArgs e)
        {
            var stateManager    = ((AdventureWorksLTEntities)sender).ObjectStateManager;
            var changedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added);

            // validation check logic
            throw new ValidationException("Something went wrong.");
        }
        /// <summary>
        /// Private extension method for ObjectStateManager class
        /// Dump all tracking info to a string 
        /// </summary>
        /// <param name="manager">ObjectStateManager</param>
        /// <param name="objectStateEntries">Collection of ObjectStateEntries. If null, then all entities will be displayed</param>
        /// <param name="entityKey">EntityKey of given entity. If null, then all entities will be displayed</param>
        /// <param name="asHtml">Output string as HTML</param>
        /// <returns>String with tracking info about entries</returns>
        private static string Dump(
          ObjectStateManager manager,
          IEnumerable<ObjectStateEntry> objectStateEntries,
          EntityKey entityKey,
          bool asHtml)
        {
            StringBuilder dump = new StringBuilder();

            if (entityKey != null)
            {
                objectStateEntries = new List<ObjectStateEntry>();
                (objectStateEntries as List<ObjectStateEntry>).Add(manager.GetObjectStateEntry(entityKey));
            }
            else if (objectStateEntries == null)
            {
                objectStateEntries = manager.GetObjectStateEntries(~EntityState.Detached);
            }

            dump.AppendFormat("ObjectStateManager entries : # {0}\n", objectStateEntries.Count());

            foreach (var entry in objectStateEntries)
            {
                dump.Append(ObjectStateEntryToString(entry));

                if (entry.State == EntityState.Added)
                {
                    for (int i = 0; i < entry.CurrentValues.FieldCount; i++)
                    {
                        dump.AppendFormat("\n\t- {0} = {1}",
                          entry.CurrentValues.GetName(i),
                          ObjectToString(entry.CurrentValues[i]));
                    }
                }
                else if (entry.State == EntityState.Modified)
                {
                    foreach (string prop in entry.GetModifiedProperties())
                    {
                        dump.AppendFormat("\n\t- {0} : {1} -> {2}",
                            prop,
                            ObjectToString(entry.OriginalValues[prop]),
                            ObjectToString(entry.CurrentValues[prop]));
                    }
                }
            }

            if (asHtml)
            {
                dump.Replace("\n", "<br />");
                dump.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            else
            {
                dump.Replace("<b>", "");
                dump.Replace("</b>", "");
            }

            return dump.ToString();
        }
        public static IEnumerable <ObjectStateEntry> GetObjectStateEntries(this ObjectStateManager osm)
        {
            var typeEntries = from entry in osm.GetObjectStateEntries
                                  (EntityState.Added | EntityState.Deleted
                                  | EntityState.Modified | EntityState.Unchanged)
                              select entry;

            return(typeEntries);
        }
        GetObjectStateEntries <TEntity>(this ObjectStateManager osm, EntityState state)
        {
            var typeEntries =
                from entry in osm.GetObjectStateEntries(state)
                where entry.Entity is TEntity
                select entry;

            return(typeEntries);
        }
Exemplo n.º 19
0
        private IEnumerable <Tuple <IBusinessLogic, IEnumerable <string> > > FilterToBusinessLogic(EntityState entityState)
        {
            var objectStateEntries = ObjectStateManager.GetObjectStateEntries(entityState).ToList();

            foreach (ObjectStateEntry objectStateEntry in objectStateEntries.Where(item => item.Entity is IBusinessLogic))
            {
                yield return(Tuple.Create((IBusinessLogic)objectStateEntry.Entity, objectStateEntry.GetModifiedProperties()));
            }
        }
        public bool HasPendingChanges()
        {
            System.Data.EntityState state = System.Data.EntityState.Added | System.Data.EntityState.Detached | System.Data.EntityState.Modified;
            foreach (var i in ObjectStateManager.GetObjectStateEntries(state))
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 21
0
 ///Este metodo obtiene todas las entidades agregadas, borradas o modificadas del contexto actual
 private IEnumerable <ObjectStateEntry> obtenerEntidadesConCambios()
 {
     return(from e in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
            where
            e.State != EntityState.Detached &&
            e.IsRelationship == false &&
            e.Entity != null &&
            e.Entity is IEntidadModificable
            select e);
 }
Exemplo n.º 22
0
 private void EntitySavingChanges(object sender, EventArgs e)
 {
     ObjectStateManager
     .GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
     .Where(entry => entry.Entity is IValidatable).ToList().ForEach(entry =>
     {
         var entity = entry.Entity as IValidatable;
         entity.Validate(entry, ValidationContext);
     });
 }
        public static IEnumerable <ObjectStateEntry> GetObjectStateEntries <TEntity>(this ObjectStateManager osm)
        {
            //this method takes advantage of the previous overload to return all EntityStates
            var typeEntries =
                from entry in osm.GetObjectStateEntries()
                where entry.Entity is TEntity
                select entry;

            return(typeEntries);
        }
Exemplo n.º 24
0
        private void button15_Click(object sender, EventArgs e)
        {
            //var Product= this.db.Products.First();
            //Product.ProductName += "xxx";
            //if (this.db.Entry(Product).State == EntityState.Modified)
            //{
            //    //modify  entity
            //    MessageBox.Show(this.db.Entry(Product).State.ToString());
            //}



            //ObjectContext 要透過介面變數拿
            ObjectStateManager objectStateManager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;

            //很多功能在 ObjectContext
            //確保 System.Data.Entity.Core.Objects.ObjectStateEntry 變更與 System.Data.Entity.Core.Objects.ObjectStateManager
            // 所追蹤之所有物件中的變更同步
            ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext.DetectChanges();


            //this.dataGridView1.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Added);
            //this.dataGridView2.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Deleted);
            //this.dataGridView3.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Modified);

            this.dataGridView1.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Added).Select(entity =>
            {
                dynamic d = entity.Entity;
                return(new { entity.EntityKey, entity.State, ProductID = d.ProductID, ProductName = d.ProductName });
            }).ToList();

            this.dataGridView2.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Deleted).Select(entity =>
            {
                dynamic d = entity.Entity;
                return(new { entity.EntityKey, entity.State, ProductID = d.ProductID, ProductName = d.ProductName });
            }).ToList();
            this.dataGridView3.DataSource = objectStateManager.GetObjectStateEntries(EntityState.Modified).Select(entity =>
            {
                dynamic d = entity.Entity;
                return(new { entity.EntityKey, entity.State, ProductID = d.ProductID, ProductName = d.ProductName });
            }).ToList();
        }
Exemplo n.º 25
0
        /// <summary>
        /// 获取数据上下文的变更日志信息
        /// </summary>
        public static IEnumerable <DataLog> GetEntityOperateLogs(this DbContext dbContext)
        {
            string[] nonLoggingTypeNames = { };

            ObjectContext      objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
            ObjectStateManager manager       = objectContext.ObjectStateManager;

            IEnumerable <ObjectStateEntry> entries = manager.GetObjectStateEntries(EntityState.Added)
                                                     .Where(entry => entry.Entity != null && !nonLoggingTypeNames.Contains(entry.Entity.GetType().FullName));
            IEnumerable <DataLog> logs = entries.Select(GetAddedLog);

            entries = manager.GetObjectStateEntries(EntityState.Modified)
                      .Where(entry => entry.Entity != null && !nonLoggingTypeNames.Contains(entry.Entity.GetType().FullName));
            logs = logs.Union(entries.Select(GetModifiedLog));

            entries = manager.GetObjectStateEntries(EntityState.Deleted)
                      .Where(entry => entry.Entity != null && !nonLoggingTypeNames.Contains(entry.Entity.GetType().FullName));
            logs = logs.Union(entries.Select(GetDeletedLog));
            return(logs);
        }
Exemplo n.º 26
0
        protected virtual void Audit(object sender, EventArgs e)
        {
            if (AuditedEntities == null)
            {
                var AuditedEntities1 = Assembly.GetExecutingAssembly()
                                       .GetReferencedAssemblies()
                                       .SelectMany(asm => Assembly.Load(asm).GetTypes())
                                       .Concat(Assembly.GetExecutingAssembly().GetTypes());
                var collAE = AuditedEntities1.ToList();
                for (int i = 0; i < collAE.Count; i++)
                {
                    try
                    {
                        var myType  = collAE[i];
                        var myTypeI = myType.GetInterface(typeof(IAudit <>).FullName);
                    }
                    catch (Exception ex)
                    {
                        string s = ex.ToString();
                    }
                }

                var AuditedEntities2 = AuditedEntities1.Where(t => t.GetInterface(typeof(IAudit <>).FullName) != null);
                var AuditedEntities3 = AuditedEntities2.ToDictionary(t =>
                                                                     t.GetInterface(typeof(IAudit <>).FullName).GetGenericArguments().First(),
                                                                     t => t
                                                                     );
                AuditedEntities = AuditedEntities3;
            }

            var changes = ObjectStateManager.GetObjectStateEntries(EntityState.Added).Concat(
                ObjectStateManager.GetObjectStateEntries(EntityState.Modified)).Concat(
                ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
                          .Where(c => c.Entity.GetType().GetInterface(typeof(IAudit <>).FullName) == null && GetAuditType(c.Entity.GetType()) != null).ToArray();

            if (changes.Length == 0)
            {
                return;
            }

            PendingAudits = changes.Select(c => new { Audit = new AuditLog
                                                      {
                                                          AuditDate          = DateTime.UtcNow,
                                                          Type               = c.State.ToString(),
                                                          EntityType         = c.Entity.GetType().Name,
                                                          UserKey            = Convert.ToString(_currUser),
                                                          EntityBeingAudited = (EntityObject)c.Entity,
                                                          KeyValue           = ((IEntityWithKey)c.Entity).EntityKey
                                                      }, Entries = c.GetModifiedProperties()
                                                                   .Where(fld => !Equals(c.OriginalValues[fld], c.CurrentValues[fld]) && string.Compare(fld, "timestamp", true) != 0)
                                                                   .Select(fld => GetAuditEntity(fld, c))
                                                                   .Where(ae => ae != null)
                                                                   .ToArray() }).Where(p => p.Entries.Length > 0 || p.Audit.EntityBeingAudited.EntityState != EntityState.Modified).ToDictionary(p => p.Audit, p => p.Entries);
        }
Exemplo n.º 27
0
 public override int SaveChanges(SaveOptions options)
 {
     foreach (ObjectStateEntry objectStateEntry in ObjectStateManager.GetObjectStateEntries(EntityState.Added))
     {
         if (objectStateEntry.Entity is Event)
         {
             ((Event)objectStateEntry.Entity).BeforeSave();
         }
     }
     return(base.SaveChanges(options));
 }
Exemplo n.º 28
0
        /// <summary>
        /// Sauvegarde les entités
        /// </summary>
        /// <returns>Le nombre d'entités modifiées.</returns>
        public override async Task <int> SaveChangesAsync()
        {
            UpdateCurrentEditingUsername();

            IEnumerable <ObjectStateEntry> stateEntries = ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                                                          .Where(e => (e.Entity as IAuditable)?.CustomAudit == false);

            int userId = GetUserId(CurrentEditingUsername);

            foreach (ObjectStateEntry stateEntry in stateEntries)
            {
                UpdateAuditInformation(stateEntry, userId);
            }

#if DEBUG
            // Utile pour inspection en mode débug uniquement
            KeyValuePair <EntityState, object>[] allchangedEntities = ObjectStateManager.GetObjectStateEntries(
                EntityState.Added |
                EntityState.Modified |
                EntityState.Deleted)
                                                                      .Where(e => e.Entity is IObjectWithChangeTracker)
                                                                      .Select(entry => new KeyValuePair <EntityState, object>(entry.State, entry.Entity))
                                                                      .ToArray();

            IGrouping <EntityKey, ObjectStateEntry>[] duplicatedKeys = ObjectStateManager.GetObjectStateEntries(EntityState.Added |
                                                                                                                EntityState.Modified |
                                                                                                                EntityState.Unchanged |
                                                                                                                EntityState.Deleted)
                                                                       .Where(e => e.Entity is IObjectWithChangeTracker)
                                                                       .GroupBy(e => e.EntityKey)
                                                                       .Where(g => g.Count() > 1)
                                                                       .ToArray();
#endif

            IObjectWithChangeTracker[] allEntities = ObjectStateManager.GetObjectStateEntries(
                EntityState.Added |
                EntityState.Modified |
                EntityState.Unchanged |
                EntityState.Deleted)
                                                     .Select(entry => entry.Entity)
                                                     .OfType <IObjectWithChangeTracker>()
                                                     .ToArray();

            int ret = await base.SaveChangesAsync();

            // Passer tout en unchanged
            foreach (IObjectWithChangeTracker entity in allEntities)
            {
                entity.AcceptChanges();
            }

            return(ret);
        }
Exemplo n.º 29
0
        public IOven <TChangeSet, TPrincipal> Log(ObjectStateManager objectStateManager)
        {
            var entries = objectStateManager.GetObjectStateEntries(EntityState.Added
                                                                   | EntityState.Modified
                                                                   | EntityState.Deleted);

            foreach (var entry in entries)
            {
                process(entry);
            }

            return(recorder);
        }
Exemplo n.º 30
0
        public override int SaveChanges(SaveOptions options)
        {
            var si = SessionInfo.Get();

            if (sharedClient != null && si.currentTopicId != -1 && si.discussion != null)
            {
                //added
                foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added))
                {
                    if (entry.Entity is ArgPoint)
                    {
                        ((ArgPoint)entry.Entity).ChangesPending = false;
                        sharedClient.clienRt.SendStatsEvent(StEvent.BadgeCreated,
                                                            si.person.Id, si.discussion.Id, si.currentTopicId,
                                                            DeviceType.Wpf);
                    }
                }

                //edited
                foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
                {
                    if (entry.Entity is ArgPoint)
                    {
                        ((ArgPoint)entry.Entity).ChangesPending = false;
                        sharedClient.clienRt.SendStatsEvent(StEvent.BadgeEdited,
                                                            SessionInfo.Get().person.Id,
                                                            si.discussion.Id,
                                                            si.currentTopicId,
                                                            DeviceType.Wpf);
                    }
                }

                //sources/comments/media modified
                foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged))
                {
                    if (entry.Entity is ArgPoint)
                    {
                        var ap = (ArgPoint)entry.Entity;
                        if (ap.ChangesPending)
                        {
                            ap.ChangesPending = false;
                            sharedClient.clienRt.SendStatsEvent(StEvent.BadgeEdited,
                                                                si.person.Id, si.discussion.Id, si.currentTopicId,
                                                                DeviceType.Wpf);
                        }
                    }
                }
            }

            return(base.SaveChanges(options));
        }
Exemplo n.º 31
0
    void OnSavingChanges(object sender, EventArgs e)
    {
        var modifiedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

        foreach (var entry in modifiedEntities)
        {
            var modifiedProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();
            var currentValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues;
            foreach (var propName in modifiedProps)
            {
                var newValue = currentValues[propName];
                //log changes
            }
        }
    }
Exemplo n.º 32
0
        /// <summary>
        /// Keep the member list synchronized with the one that is saved to database.
        /// </summary>
        /// <param name="objectStateManager"></param>
        private static void RefreshMembersListTask(ObjectStateManager objectStateManager)
        {
            using(new DebugTimer("Refresh members list"))
            {
                IEnumerable<ObjectStateEntry> addedEntries = objectStateManager.GetObjectStateEntries(System.Data.EntityState.Added);
                IEnumerable<ObjectStateEntry> deletedEntries = objectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted);
                IEnumerable<ObjectStateEntry> modifiedEntries = objectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);

                HandleAddedMembers(addedEntries);
                HandleDeletedMembers(deletedEntries);
                HandleModifiedMembers(modifiedEntries);
                Debug.Print("Got {0} added, {1} deleted and {2} modified members", addedEntries.Count(), deletedEntries.Count(), modifiedEntries.Count());
            }

            if (RefreshFinished != null)
                RefreshFinished(null, null);
        }