Ejemplo n.º 1
0
        private void ProcessAutogeneratedKeys()
        {
            var tempKeys = EntitiesWithAutoGeneratedKeys.Cast <EFEntityInfo>().Where(
                entityInfo => entityInfo.AutoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.KeyGenerator)
                           .Select(ei => new TempKeyInfo(ei))
                           .ToList();

            if (tempKeys.Count == 0)
            {
                return;
            }
            if (this.KeyGenerator == null)
            {
                this.KeyGenerator = GetKeyGenerator();
            }
            this.KeyGenerator.UpdateKeys(tempKeys);
            tempKeys.ForEach(tki => {
                // Clever hack - next 3 lines cause all entities related to tki.Entity to have
                // their relationships updated. So all related entities for each tki are updated.
                // Basically we set the entity to look like a preexisting entity by setting its
                // entityState to unchanged.  This is what fixes up the relations, then we set it back to added
                // Now when we update the pk - all fks will get changed as well.  Note that the fk change will only
                // occur during the save.
                var entry = GetObjectStateEntry(tki.Entity);
                entry.ChangeState(System.Data.EntityState.Unchanged);
                entry.ChangeState(System.Data.EntityState.Added);
                var val = ConvertValue(tki.RealValue, tki.Property.PropertyType);
                tki.Property.SetValue(tki.Entity, val, null);
            });
        }
Ejemplo n.º 2
0
        private List <KeyMapping> UpdateAutoGeneratedKeys()
        {
            // where clause is necessary in case the Entities were suppressed in the beforeSave event.
            var keyMappings = EntitiesWithAutoGeneratedKeys.Cast <EFEntityInfo>()
                              .Where(entityInfo => entityInfo.ObjectStateEntry != null)
                              .Select(entityInfo => {
                var autoGeneratedKey = entityInfo.AutoGeneratedKey;
                if (autoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.Identity)
                {
                    autoGeneratedKey.RealValue = GetOsePropertyValue(entityInfo.ObjectStateEntry, autoGeneratedKey.PropertyName);
                }
                return(new KeyMapping()
                {
                    EntityTypeName = entityInfo.Entity.GetType().FullName,
                    TempValue = autoGeneratedKey.TempValue,
                    RealValue = autoGeneratedKey.RealValue
                });
            });

            return(keyMappings.ToList());
        }