public SaveResult SaveWithAuditFields([FromBody] SaveBundle saveBundle)
        {
            return(SaveChangesCore(saveBundle, configurator => configurator.BeforeSaveEntityChanges((entityInfo, context) =>
            {
                var entity = entityInfo.Entity as User;
                if (entity == null)
                {
                    return;
                }

                var userId = 12345;
                if (entityInfo.EntityState == EntityState.Added)
                {
                    entity.CreatedBy = "test";
                    entity.CreatedByUserId = userId;
                    entity.CreatedDate = DateTime.Now;
                    entity.ModifiedBy = "test";
                    entity.ModifiedByUserId = userId;
                    entity.ModifiedDate = DateTime.Now;
                }
                else if (entityInfo.EntityState == EntityState.Modified)
                {
                    entity.ModifiedBy = "test";
                    entity.ModifiedByUserId = userId;
                    entity.ModifiedDate = DateTime.Now;
                }
            })));
        }
 public SaveResult SaveWithEntityErrorsException([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeApplyChanges(
                                context =>
     {
         var saveMap = context.SaveMap;
         if (saveMap.TryGetValue(typeof(Order), out var orderInfos))
         {
             var errors = orderInfos.Select(oi =>
             {
                 return new EntityError
                 {
                     EntityTypeName = typeof(Order).FullName,
                     ErrorMessage = "Cannot save orders with this save method",
                     ErrorName = "WrongMethod",
                     KeyValues = new object[] { ((Order)oi.ClientEntity).OrderID },
                     PropertyName = "OrderID"
                 };
             });
             var ex = new EntityErrorsException("test of custom exception message", errors);
             // if you want to see a different error status code use this.
             // ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
             throw ex;
         }
     })));
 }
        public SaveResult SaveCheckUnmappedPropertySerialized([FromBody] SaveBundle saveBundle)
        {
            return(SaveChangesCore(saveBundle, configurator => configurator.AfterCreateEntityInfo((entityInfo, saveOptions) =>
            {
                var unmappedValue = (string)entityInfo.UnmappedValuesMap["MyUnmappedProperty"];
                if (unmappedValue != "ANYTHING22")
                {
                    throw new Exception("wrong value for unmapped property:  " + unmappedValue);
                }

                var anotherOne = entityInfo.UnmappedValuesMap["AnotherOne"];
                if (((dynamic)anotherOne).z[5].foo.Value != 4)
                {
                    throw new Exception("wrong value for 'anotherOne.z[5].foo'");
                }

                if (((dynamic)anotherOne).extra.Value != 666)
                {
                    throw new Exception("wrong value for 'anotherOne.extra'");
                }

                var customer = (Customer)entityInfo.ClientEntity;
                if (customer.CompanyName.ToUpper() != customer.CompanyName)
                {
                    throw new Exception("Uppercasing of company name did not occur");
                }

                return false;
            })));
        }
 public SaveResult SaveCheckInitializer([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeApplyChanges(context =>
     {
         var order = new Order {
             OrderDate = DateTime.Today
         };
         context.AddAdditionalEntity(order, EntityState.Added);
     })));
 }
        public SaveResult SaveCheckUnmappedPropertySuppressed([FromBody] SaveBundle saveBundle)
        {
            return(SaveChangesCore(saveBundle, configurator => configurator.AfterCreateEntityInfo((entityInfo, saveOptions) =>
            {
                if (entityInfo.UnmappedValuesMap != null)
                {
                    throw new Exception("unmapped properties should have been suppressed");
                }

                return false;
            })));
        }
 public SaveResult SaveWithComment([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeApplyChanges(
                                context =>
     {
         var comment = new Comment();
         var tag = context.SaveOptions.Tag.ToString();
         comment.Comment1 = (tag == null) ? "Generic comment" : tag.ToString();
         comment.CreatedOn = DateTime.Now;
         comment.SeqNum = 1;
         context.AddAdditionalEntity(comment, EntityState.Added);
     })));
 }
        public SaveResult SaveWithTransactionScope([FromBody] SaveBundle saveBundle)
        {
            var txOptions = new TransactionOptions
            {
                IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TransactionManager.DefaultTimeout,
            };

            using var txScope = new TransactionScope(TransactionScopeOption.Required, txOptions);
            var result = SaveChangesCore(saveBundle);

            txScope.Complete();
            return(result);
        }
        public SaveResult SaveCheckUnmappedProperty([FromBody] SaveBundle saveBundle)
        {
            return(SaveChangesCore(saveBundle, configurator => configurator.AfterCreateEntityInfo((entityInfo, saveOptions) =>
            {
                var unmappedValue = (string)entityInfo.UnmappedValuesMap["MyUnmappedProperty"];
                if (unmappedValue != "anything22")
                {
                    throw new Exception("wrong value for unmapped property:  " + unmappedValue);
                }

                return false;
            })));
        }
 public SaveResult SaveWithFreight2([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeSaveChanges((order, context) =>
     {
         var saveMap = context.SaveMap;
         if (saveMap.TryGetValue(typeof(Order), out var entityInfos))
         {
             foreach (var entityInfo in entityInfos)
             {
                 CheckFreight(entityInfo, context);
             }
         }
     })));
 }
 private SaveResult SaveChangesCore(SaveBundle saveBundle, Action <SaveChangesOptionsConfigurator> configureAction = null)
 {
     using var tx = _session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
     try
     {
         var result = _persistenceManager.SaveChanges(saveBundle, configureAction);
         tx.Commit();
         return(result);
     }
     catch
     {
         tx.Rollback();
         throw;
     }
 }
 public SaveResult SaveWithNoTransaction([FromBody] SaveBundle saveBundle)
 {
     return(_persistenceManager.SaveChanges(saveBundle));
 }
 public SaveResult SaveWithDbTransaction([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle));
 }
 public SaveResult SaveChanges([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle));
 }
 public SaveResult SaveAndThrow([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeApplyChanges(
                                context => throw new Exception("Deliberately thrown exception"))));
 }
Example #15
0
 public Task <SaveResult> AsyncSaveChanges(SaveBundle saveBundle)
 {
     return(_persistenceManager.SaveChangesAsync(saveBundle));
 }
 public SaveResult SaveWithExit([FromBody] SaveBundle saveBundle)
 {
     return(new SaveResult {
         Entities = new List <object>(), KeyMappings = new List <KeyMapping>()
     });
 }
 public SaveResult SaveWithFreight([FromBody] SaveBundle saveBundle)
 {
     return(SaveChangesCore(saveBundle, configurator => configurator.BeforeSaveEntityChanges(CheckFreight)));
 }
Example #18
0
        public SaveBundle GetSaveBundle()
        {
            var entities   = new List <JObject>();
            var saveBundle = new SaveBundle
            {
                Entities    = entities,
                SaveOptions = new SaveOptions()
            };


            foreach (var pair in _typeEntities)
            {
                var session        = _sessionProvider.Get(pair.Key);
                var sessionImpl    = session.GetSessionImplementation();
                var context        = sessionImpl.PersistenceContext;
                var entityType     = pair.Key;
                var entityTypeInfo = pair.Value;
                var entityMetadata = entityTypeInfo.EntityMetadata;
                var persister      = entityMetadata.EntityPersister;
                foreach (var entityInfo in entityTypeInfo.EntitiesInfo.Values)
                {
                    var entity         = entityInfo.Entity;
                    var originalValues = new JObject();
                    var unmappedValues = new JObject();
                    var entityAspect   = new JObject
                    {
                        ["entityTypeName"]    = $"{entityType.Name}:#{entityType.Namespace}",
                        ["originalValuesMap"] = originalValues,
                        ["entityState"]       = entityInfo.EntityState.ToString()
                    };
                    if (entityMetadata.AutoGeneratedKeyType != AutoGeneratedKeyType.None)
                    {
                        var autoGeneratedKey =
                            new JObject
                        {
                            ["propertyName"]         = entityMetadata.IdentifierPropertyNames[0],
                            ["autoGeneratedKeyType"] = entityMetadata.AutoGeneratedKeyType.ToString()
                        };
                        entityAspect["autoGeneratedKey"] = autoGeneratedKey;
                    }

                    var entityData = new JObject();
                    for (var i = 0; i < entityMetadata.IdentifierPropertyNames.Count; i++)
                    {
                        var idPropertyName = entityMetadata.IdentifierPropertyNames[i];
                        var idValue        = GetToken(entityMetadata.IdentifierPropertyGetters[i](entity));
                        if (entityMetadata.SyntheticForeignKeyProperties.ContainsKey(idPropertyName))
                        {
                            unmappedValues.Add(idPropertyName, idValue);
                        }
                        else
                        {
                            entityData.Add(idPropertyName, idValue);
                        }
                    }

                    var propertyTypes = persister.PropertyTypes;
                    for (var i = 0; i < propertyTypes.Length; i++)
                    {
                        var propertyType = propertyTypes[i];
                        var propertyName = persister.PropertyNames[i];
                        if (propertyType.IsCollectionType)
                        {
                            continue;
                        }

                        var currentValue = persister.GetPropertyValue(entity, i);
                        if (entityMetadata.Associations.TryGetValue(propertyName, out var association))
                        {
                            var associatedEntityMetadata = _entityMetadataProvider.GetMetadata(association.EntityType);
                            for (var j = 0; j < association.ForeignKeyPropertyNames.Count; j++)
                            {
                                var fkValue        = currentValue != null ? associatedEntityMetadata.IdentifierPropertyGetters[j](currentValue) : null;
                                var fkPropertyName = association.ForeignKeyPropertyNames[j];
                                if (entityMetadata.SyntheticForeignKeyProperties.ContainsKey(fkPropertyName))
                                {
                                    unmappedValues.Add(fkPropertyName, GetToken(fkValue));
                                }
                            }

                            continue;
                        }

                        entityData.Add(propertyName, GetToken(currentValue));
                    }

                    if (context.IsEntryFor(entity))
                    {
                        var entry   = context.GetEntry(entity);
                        var idTypes = entityTypeInfo.IdentifierTypes;
                        for (var i = 0; i < idTypes.Length; i++)
                        {
                            var newId = entityMetadata.IdentifierPropertyGetters[i](entity);
                            if (idTypes[i].IsDirty(entityInfo.IdentifierValues[i], newId, sessionImpl))
                            {
                                originalValues[entityMetadata.IdentifierPropertyNames[i]] = GetToken(newId);
                            }
                        }

                        for (var i = 0; i < propertyTypes.Length; i++)
                        {
                            var propertyType = propertyTypes[i];
                            if (propertyType.IsCollectionType)
                            {
                                continue;
                            }

                            var propertyName  = persister.PropertyNames[i];
                            var originalValue = entry.LoadedState[i];
                            var currentValue  = persister.GetPropertyValue(entity, i);
                            if (!propertyTypes[i].IsDirty(originalValue, currentValue, sessionImpl))
                            {
                                continue;
                            }

                            if (entityMetadata.Associations.TryGetValue(propertyName, out var association))
                            {
                                foreach (var fkProperty in association.ForeignKeyPropertyNames)
                                {
                                    if (entityMetadata.SyntheticForeignKeyProperties.TryGetValue(fkProperty, out var syntheticProperty))
                                    {
                                        originalValues[fkProperty] = GetToken(syntheticProperty.GetIdentifierFunction(originalValue));
                                    }
                                }
                            }
                            else
                            {
                                originalValues[propertyName] = GetToken(originalValue);
                            }
                        }
                    }

                    entityData.Add("__unmapped", unmappedValues);
                    entityData.Add("entityAspect", entityAspect);
                    entities.Add(entityData);
                }
            }

            return(saveBundle);
        }
Example #19
0
 public SaveResult SaveChanges(SaveBundle saveBundle)
 {
     return(_persistenceManager.SaveChanges(saveBundle));
 }