Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            var now    = DateTime.Now;
            var userId = _currentApplicationUserService.GetCurrentUser();

            //Generate new guids for new entities if not populated by EF
            var newEntities = ChangeTracker.Entries <IEntity>().Where(x => x.State == EntityState.Added && x.Entity.Id == Guid.Empty);

            newEntities.ForEach(x => x.Entity.Id = Guid.NewGuid());

            var modifiedEntities = ChangeTracker.Entries <IMutableEntity>().Where(x => x.State == EntityState.Modified);

            foreach (var modifiedEntity in modifiedEntities)
            {
                modifiedEntity.Entity.ModifiedAt   = now;
                modifiedEntity.Entity.ModifiedById = userId;
            }

            var createdMutableEntities = ChangeTracker.Entries <IMutableEntity>().Where(x => x.State == EntityState.Added);

            foreach (var createdEntity in createdMutableEntities)
            {
                createdEntity.Entity.CreatedAt    = now;
                createdEntity.Entity.CreatedById  = userId;
                createdEntity.Entity.ModifiedAt   = now;
                createdEntity.Entity.ModifiedById = userId;
            }

            var createdImmutableEntities = ChangeTracker.Entries <IImmutableEntity>().Where(x => x.State == EntityState.Added);

            foreach (var createdEntity in createdImmutableEntities)
            {
                createdEntity.Entity.CreatedAt   = now;
                createdEntity.Entity.CreatedById = userId;
            }

            return(base.SaveChanges());
        }