Example #1
0
        protected virtual bool PopulateInsertValues(IDbCommand command, object parentOfObjectToSave, Table parentTableOfObjectToSave,
                                                    object objectToSave, ColumnCachedValues cachedValues,
                                                    ICollection <SameTableElementInfo> sameTableElements)
        {
            bool anyPopulated = false;

            if (sameTableElements != null)
            {
                foreach (SameTableElementInfo sameTableElementInfo in sameTableElements)
                {
                    object objectInstance = sameTableElementInfo.GetMemberValue(objectToSave);

                    if (PopulateInsertValues(command, objectToSave, parentTableOfObjectToSave, objectInstance, cachedValues,
                                             sameTableElementInfo.DirectColumns))
                    {
                        anyPopulated = true;
                    }
                    if (PopulateInsertValues(command, objectToSave, parentTableOfObjectToSave, objectInstance, cachedValues,
                                             sameTableElementInfo.ChildSameTableElements))
                    {
                        anyPopulated = true;
                    }
                }
            }
            return(anyPopulated);
        }
        public virtual Dictionary <string, int> SaveToDatabase(object objectToSave, SpringBaseDao baseDao, Type mappingAttributesType, bool inheritMappingAttributes)
        {
            Type           objectToSaveType = objectToSave.GetType();
            MappingContext mappingContext   = MappingContext.GetMappingContext(objectToSaveType, mappingAttributesType, inheritMappingAttributes);

            BuildObjectSql(mappingContext, baseDao);

            IBeforeSaveToDatabase beforeSaveToDatabase = objectToSave as IBeforeSaveToDatabase;

            if (beforeSaveToDatabase != null)
            {
                beforeSaveToDatabase.BeforeSaveToDatabase();
            }

            Dictionary <string, int> insertRowCounts = new Dictionary <string, int>();

            baseDao.TransactionTemplate.Execute(delegate
            {
                baseDao.AdoTemplate.ClassicAdoTemplate.Execute(delegate(IDbCommand command)
                {
                    ColumnCachedValues cachedValues = new ColumnCachedValues();
                    SaveToDatabase(null, objectToSave, null, cachedValues, mappingContext,
                                   insertRowCounts, command);
                    return(null);
                });
                return(null);
            });
            return(insertRowCounts);
        }
Example #3
0
        protected virtual void LoadSameTableInstancesNew(object objectToSet, ICollection <SameTableElementInfo> sameTableElements,
                                                         ColumnCachedValues cachedValues, IDataReader reader,
                                                         ref int readerIndex, ref bool anyObjectToSetFieldsWereSet)
        {
            if (sameTableElements != null)
            {
                if (objectToSet.GetType().Name == "Parameter")
                {
                }
                foreach (SameTableElementInfo sameTableElementInfo in sameTableElements)
                {
                    object sameTableElementObjectToSet = null;
                    foreach (Column column in sameTableElementInfo.DirectColumns)
                    {
                        if (!column.NoLoad)
                        {
                            object value = reader.GetValue(readerIndex++);

                            if (value == DBNull.Value)
                            {
                                value = null;
                            }

                            if (value != null)
                            {
                                if (sameTableElementObjectToSet == null)
                                {
                                    sameTableElementObjectToSet = Activator.CreateInstance(sameTableElementInfo.MemberType);
                                }
                                column.SetSelectColumnValue(sameTableElementObjectToSet, value, cachedValues);
                            }
                        }
                    }
                    if (sameTableElementObjectToSet != null)
                    {
                        sameTableElementInfo.SetMemberValue(objectToSet, sameTableElementObjectToSet);
                        anyObjectToSetFieldsWereSet = true;
                        LoadSameTableInstancesNew(sameTableElementObjectToSet, sameTableElementInfo.ChildSameTableElements,
                                                  cachedValues, reader, ref readerIndex, ref anyObjectToSetFieldsWereSet);
                    }
                    else if (!CollectionUtils.IsNullOrEmpty(sameTableElementInfo.ChildSameTableElements))
                    {
                        // Need to check to see if any children will be set in same table
                        sameTableElementObjectToSet = Activator.CreateInstance(sameTableElementInfo.MemberType);
                        bool anyObjectToSetChildFieldsWereSet = false;
                        LoadSameTableInstancesNew(sameTableElementObjectToSet, sameTableElementInfo.ChildSameTableElements,
                                                  cachedValues, reader, ref readerIndex, ref anyObjectToSetChildFieldsWereSet);
                        if (anyObjectToSetChildFieldsWereSet)
                        {
                            sameTableElementInfo.SetMemberValue(objectToSet, sameTableElementObjectToSet);
                            anyObjectToSetFieldsWereSet = true;
                        }
                    }
                }
            }
        }
        public virtual Dictionary <string, int> SaveToDatabase <T>(IEnumerable <T> objectsToSave, SpringBaseDao baseDao,
                                                                   bool deleteAllBeforeSave, Type mappingAttributesType,
                                                                   bool inheritMappingAttributes)
        {
            Type           objectToSaveType = typeof(T);
            MappingContext mappingContext   = MappingContext.GetMappingContext(objectToSaveType, mappingAttributesType, inheritMappingAttributes);

            BuildObjectSql(mappingContext, baseDao);

            Dictionary <string, int> insertRowCounts = new Dictionary <string, int>();

            baseDao.TransactionTemplate.Execute(delegate
            {
                baseDao.AdoTemplate.ClassicAdoTemplate.Execute(delegate(IDbCommand command)
                {
                    if (deleteAllBeforeSave)
                    {
                        DeleteAllFromDatabase(objectToSaveType, baseDao, mappingAttributesType);
                    }
                    int count = 0;
                    CollectionUtils.ForEach(objectsToSave, delegate(T objectToSave)
                    {
                        ++count;
                        bool doSave = true;
                        ICanSaveToDatabase checkToSaveToDatabase = objectToSave as ICanSaveToDatabase;
                        if (checkToSaveToDatabase != null)
                        {
                            if (!checkToSaveToDatabase.CanSaveToDatabase(this, baseDao))
                            {
                                doSave = false;
                            }
                        }
                        if (doSave)
                        {
                            IBeforeSaveToDatabase beforeSaveToDatabase = objectToSave as IBeforeSaveToDatabase;
                            if (beforeSaveToDatabase != null)
                            {
                                beforeSaveToDatabase.BeforeSaveToDatabase();
                            }

                            ColumnCachedValues cachedValues = new ColumnCachedValues();
                            SaveToDatabase(null, objectToSave, null, cachedValues, mappingContext, insertRowCounts, command);
                        }
                    });
                    return(null);
                });
                return(null);
            });
            return(insertRowCounts);
        }
Example #5
0
        public virtual IList LoadFromDatabase(Type typeToLoad, SpringBaseDao baseDao,
                                              IDictionary <string, DbAppendSelectWhereClause> appendSelectWhereClauses,
                                              Type mappingAttributesType)
        {
            MappingContext mappingContext = MappingContext.GetMappingContext(typeToLoad, mappingAttributesType);

            BuildObjectSql(mappingContext, baseDao);

            Dictionary <object, IList> list = null;

            baseDao.AdoTemplate.ClassicAdoTemplate.Execute(delegate(IDbCommand command)
            {
                ColumnCachedValues cachedValues = new ColumnCachedValues();
                list =
                    LoadObjectInstancesToList(typeToLoad, null, null, appendSelectWhereClauses, cachedValues, mappingContext, command);
                return(null);
            });
            if (list != null)
            {
                IList rtnList = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(typeToLoad));
                foreach (KeyValuePair <object, IList> pair in list)
                {
                    foreach (object listElement in pair.Value)
                    {
                        rtnList.Add(listElement);
                    }
                }
                foreach (object obj in rtnList)
                {
                    IAfterLoadFromDatabase afterLoadFromDatabase = obj as IAfterLoadFromDatabase;
                    if (afterLoadFromDatabase != null)
                    {
                        afterLoadFromDatabase.AfterLoadFromDatabase();
                    }
                }

                return(rtnList);
            }
            else
            {
                return(null);
            }
        }
Example #6
0
        protected virtual void LoadSameTableInstances(object objectToSet, ICollection <SameTableElementInfo> sameTableElements,
                                                      ColumnCachedValues cachedValues, IDataReader reader,
                                                      ref int readerIndex, ref bool anyObjectToSetFieldsWereSet)
        {
            if (sameTableElements != null)
            {
                foreach (SameTableElementInfo sameTableElementInfo in sameTableElements)
                {
                    object sameTableElementObjectToSet = null;
                    foreach (Column column in sameTableElementInfo.DirectColumns)
                    {
                        if (!column.NoLoad)
                        {
                            object value = reader.GetValue(readerIndex++);

                            if (value == DBNull.Value)
                            {
                                value = null;
                            }

                            if (value != null)
                            {
                                if (sameTableElementObjectToSet == null)
                                {
                                    sameTableElementObjectToSet = Activator.CreateInstance(sameTableElementInfo.MemberType);
                                }
                                column.SetSelectColumnValue(sameTableElementObjectToSet, value, cachedValues);
                            }
                        }
                    }
                    if (sameTableElementObjectToSet != null)
                    {
                        sameTableElementInfo.SetMemberValue(objectToSet, sameTableElementObjectToSet);
                        anyObjectToSetFieldsWereSet = true;
                    }

                    LoadSameTableInstances(objectToSet, sameTableElementInfo.ChildSameTableElements,
                                           cachedValues, reader, ref readerIndex, ref anyObjectToSetFieldsWereSet);
                }
            }
        }
Example #7
0
        protected virtual bool PopulateInsertValues(IDbCommand command, object parentOfObjectToSave, Table parentTableOfObjectToSave,
                                                    object objectToSave, ColumnCachedValues cachedValues, ICollection <Column> columns)
        {
            bool anyPopulated = false;

            if (columns != null)
            {
                foreach (Column column in columns)
                {
                    if (!column.NoLoad)
                    {
                        IDbDataParameter parameter = command.CreateParameter();
                        parameter.DbType        = column.ColumnType.Value;
                        parameter.Direction     = ParameterDirection.Input;
                        parameter.Size          = column.ColumnSize;
                        parameter.ParameterName = column.ColumnName;
                        if (column.IsForeignKey)
                        {
                            Table foreignTable = ((ForeignKeyColumn)column).ForeignTable;
                            ExceptionUtils.ThrowIfNull(parentTableOfObjectToSave, "parentTableOfObjectToSave");
                            if (foreignTable == parentTableOfObjectToSave)
                            {
                                parameter.Value = column.GetInsertColumnValue(parentOfObjectToSave, objectToSave, cachedValues);
                            }
                            else
                            {
                                parameter.Value = DBNull.Value;
                            }
                        }
                        else
                        {
                            parameter.Value = column.GetInsertColumnValue(parentOfObjectToSave, objectToSave, cachedValues);
                        }
                        command.Parameters.Add(parameter);
                        anyPopulated = true;
                    }
                }
            }
            return(anyPopulated);
        }
Example #8
0
        protected virtual Dictionary <object, IList> LoadObjectInstancesToList(Type objectTypeToLoad, Table objectTypeToLoadTable, Dictionary <object, object> parentPKToObjectMap,
                                                                               IDictionary <string, DbAppendSelectWhereClause> appendSelectWhereClauseMap,
                                                                               ColumnCachedValues cachedValues, MappingContext mappingContext, IDbCommand command)
        {
            if (objectTypeToLoadTable == null)
            {
                objectTypeToLoadTable = mappingContext.GetTableForType(objectTypeToLoad);
            }
            Dictionary <object, IList> list = null;

            if (!string.IsNullOrEmpty(objectTypeToLoadTable.SelectSql))
            {
                command.CommandText = objectTypeToLoadTable.SelectSql;
                command.CommandType = CommandType.Text;
                command.Parameters.Clear();

                AppendSelectWhereClause(objectTypeToLoadTable.TableName, command, appendSelectWhereClauseMap);

                list = LoadObjectInstancesToList(objectTypeToLoadTable, parentPKToObjectMap, appendSelectWhereClauseMap, cachedValues, mappingContext, command);
            }
            return(list);
        }
Example #9
0
        public virtual bool PopulateInsertValues(IDbCommand command, object parentOfObjectToSave, Table parentTableOfObjectToSave,
                                                 object objectToSave, ColumnCachedValues cachedValues)
        {
            bool anyPopulated = false;

            if (!string.IsNullOrEmpty(InsertSql))
            {
                command.CommandText = InsertSql;
                command.CommandType = CommandType.Text;
                command.Parameters.Clear();

                if (PopulateInsertValues(command, parentOfObjectToSave, parentTableOfObjectToSave, objectToSave, cachedValues, DirectColumns))
                {
                    anyPopulated = true;
                }
                if (PopulateInsertValues(command, parentOfObjectToSave, parentTableOfObjectToSave, objectToSave, cachedValues, m_ChildSameTableElements))
                {
                    anyPopulated = true;
                }
            }
            return(anyPopulated);
        }
Example #10
0
        protected virtual Dictionary <object, IList> LoadObjectInstancesToList(Table tableOfObjectsToLoad, Dictionary <object, object> parentPKToObjectMap,
                                                                               IDictionary <string, DbAppendSelectWhereClause> appendSelectWhereClauseMap,
                                                                               ColumnCachedValues cachedValues, MappingContext mappingContext,
                                                                               IDbCommand command)
        {
            Dictionary <object, IList>  list = null;
            Dictionary <object, bool>   anyInstanceFieldsWereSetMap = null;
            Dictionary <object, object> pkToObjectMap = null;

            bool isVirtualObjectTable             = tableOfObjectsToLoad.IsVirtualTable;
            bool isCustomXmlStringFormatTypeTable = false;

            if (isVirtualObjectTable)
            {
                isCustomXmlStringFormatTypeTable = tableOfObjectsToLoad.TableRootType.IsSubclassOf(typeof(CustomXmlStringFormatTypeBase));
            }

            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    int    readerIndex = 0;
                    object pk = null, fk = null, pkKey = null, fkKey = null;
                    bool   skip = false;
                    bool   anyObjectToSetFieldsWereSet = false;
                    Column pkColumn = null, fkColumn = null;
                    object objectToSet = null;
                    // isVirtualObjectTable == true if this table represents a string[], int[], etc. member
                    foreach (Column column in tableOfObjectsToLoad.DirectColumns)
                    {
                        if (!column.NoLoad)
                        {
                            object value = reader.GetValue(readerIndex++);

                            if (value == DBNull.Value)
                            {
                                value = null;
                            }

                            if (column.IsPrimaryKey)
                            {
                                pkKey    = value + "_" + tableOfObjectsToLoad.TableName;
                                pkColumn = column;
                                pk       = value;
                            }
                            else if (column.IsForeignKey)
                            {
                                if (value != null)
                                {
                                    fkKey = value + "_" + ((ForeignKeyColumn)column).ForeignTable.TableName;
                                    if (fkColumn != null)
                                    {
                                        if (pk != null)
                                        {
                                            throw new ArgException("The table \"{0}\" has a row with a primary key of \"{1}\" that has more than one foreign key specified.  Please specify only one foreign key per row for this table.",
                                                                   column.Table.TableName, pk.ToString());
                                        }
                                        else
                                        {
                                            throw new ArgException("The table \"{0}\" has a row that has more than one foreign key specified.  Please specify only one foreign key per row for this table.",
                                                                   column.Table.TableName);
                                        }
                                    }
                                    if (!parentPKToObjectMap.ContainsKey(fkKey))
                                    {
                                        // This object has no parent, assume we skip it
                                        skip = true;
                                        break;
                                    }
                                    fkColumn = column;
                                    fk       = value;
                                }
                            }
                            else
                            {
                                if (value != null)
                                {
                                    if (isVirtualObjectTable)
                                    {
                                        if (isCustomXmlStringFormatTypeTable)
                                        {
                                            CustomXmlStringFormatTypeBase newObjectToSet = (CustomXmlStringFormatTypeBase)Activator.CreateInstance(tableOfObjectsToLoad.TableRootType);
                                            newObjectToSet.SetValue(value);
                                            objectToSet = newObjectToSet;
                                        }
                                        else
                                        {
                                            objectToSet = column.GetSetMemberValue(value);
                                        }
                                    }
                                    else
                                    {
                                        if (objectToSet == null)
                                        {
                                            objectToSet = Activator.CreateInstance(tableOfObjectsToLoad.TableRootType);
                                        }
                                        column.SetSelectColumnValue(objectToSet, value, cachedValues);
                                        anyObjectToSetFieldsWereSet = true;
                                    }
                                }
                            }
                        }
                    }
                    if (skip)
                    {
                        continue;
                    }

                    if (objectToSet == null)
                    {
                        objectToSet = Activator.CreateInstance(tableOfObjectsToLoad.TableRootType);
                    }
                    ExceptionUtils.ThrowIfNull(pkColumn, "pkColumn");
                    ExceptionUtils.ThrowIfNull(pk, "pk");
                    if (!isVirtualObjectTable)
                    {
                        pkColumn.SetSelectColumnValue(objectToSet, pk, cachedValues);

                        if (fkColumn != null)
                        {
                            fkColumn.SetSelectColumnValue(objectToSet, fk, cachedValues);
                        }
                        else
                        {
                            if (parentPKToObjectMap != null)
                            {
                                throw new ArgException("The table \"{0}\" has a row with a primary key of \"{1}\" that does not have a foreign key specified.",
                                                       pkColumn.Table.TableName, pk.ToString());
                            }
                            fk    = pk;
                            fkKey = pkKey;
                        }
                        if (mappingContext.UseNewSameTableMapping)
                        {
                            LoadSameTableInstancesNew(objectToSet, tableOfObjectsToLoad.ChildSameTableElements, cachedValues,
                                                      reader, ref readerIndex, ref anyObjectToSetFieldsWereSet);
                        }
                        else
                        {
                            LoadSameTableInstances(objectToSet, tableOfObjectsToLoad.ChildSameTableElements, cachedValues,
                                                   reader, ref readerIndex, ref anyObjectToSetFieldsWereSet);
                        }
                    }

                    int fieldCount = reader.FieldCount;
                    if (readerIndex != fieldCount)
                    {
                        throw new IndexOutOfRangeException(string.Format("The number of selected column values ({0}) is less than the expected number ({1}) for the object \"{2}\" and sql \"{3}\".",
                                                                         reader.FieldCount.ToString(), readerIndex.ToString(),
                                                                         tableOfObjectsToLoad.TableRootType.Name, tableOfObjectsToLoad.SelectSql));
                    }
                    if (list == null)
                    {
                        list          = new Dictionary <object, IList>();
                        pkToObjectMap = new Dictionary <object, object>();
                        anyInstanceFieldsWereSetMap = new Dictionary <object, bool>();
                    }
                    IList listInstance;
                    if (!list.TryGetValue(fkKey, out listInstance))
                    {
                        listInstance = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(tableOfObjectsToLoad.TableRootType));
                        list.Add(fkKey, listInstance);
                    }
                    try
                    {
                        listInstance.Add(objectToSet);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    if (!isVirtualObjectTable)
                    {
                        pkToObjectMap.Add(pkKey, objectToSet);
                        anyInstanceFieldsWereSetMap.Add(objectToSet, anyObjectToSetFieldsWereSet);
                    }
                }
            }
            if (!isVirtualObjectTable)
            {
                if (list != null)
                {
                    // Load children
                    if (tableOfObjectsToLoad.ChildRelationMembers != null)
                    {
                        foreach (ChildRelationInfo childRelation in tableOfObjectsToLoad.ChildRelationMembers)
                        {
                            Table elementTable = null;
                            if (Utils.IsValidColumnType(childRelation.ValueType))
                            {
                                elementTable = childRelation.ChildTable;
                            }
                            if (childRelation.IsOneToMany)
                            {
                                Dictionary <object, IList> fkMap =
                                    LoadObjectInstancesToList(childRelation.ValueType, elementTable, pkToObjectMap, appendSelectWhereClauseMap, cachedValues,
                                                              mappingContext, command);
                                if (fkMap != null)
                                {
                                    foreach (KeyValuePair <object, IList> pair in fkMap)
                                    {
                                        object objectToSet = pkToObjectMap[pair.Key];
                                        if (childRelation.ParentToMemberChain != null)
                                        {
                                            foreach (SameTableElementInfo sameTableElementInfo in childRelation.ParentToMemberChain)
                                            {
                                                object childObjectToSet = sameTableElementInfo.GetMemberValue(objectToSet);
                                                if (childObjectToSet == null)
                                                {
                                                    childObjectToSet = Activator.CreateInstance(sameTableElementInfo.MemberType);
                                                }
                                                objectToSet = childObjectToSet;
                                            }
                                        }
                                        DebugUtils.AssertDebuggerBreak(pair.Value != null);
                                        childRelation.SetMemberValue(objectToSet, pair.Value);
                                        anyInstanceFieldsWereSetMap[objectToSet] = true;
                                    }
                                }
                            }
                            else // One to one
                            {
                                Dictionary <object, IList> fkMap =
                                    LoadObjectInstancesToList(childRelation.ValueType, elementTable, pkToObjectMap, appendSelectWhereClauseMap, cachedValues,
                                                              mappingContext, command);
                                if (fkMap != null)
                                {
                                    foreach (KeyValuePair <object, IList> pair in fkMap)
                                    {
                                        if (pair.Value.Count != 1)
                                        {
                                            throw new InvalidOperationException(string.Format("Relation is One-To-One but got more than one element: {0}",
                                                                                              childRelation.ToString()));
                                        }
                                        object itemToSet = CollectionUtils.FirstItem(pair.Value);
                                        DebugUtils.AssertDebuggerBreak(itemToSet != null);
                                        object objectToSet = pkToObjectMap[pair.Key];
                                        if (childRelation.ParentToMemberChain != null)
                                        {
                                            foreach (SameTableElementInfo sameTableElementInfo in childRelation.ParentToMemberChain)
                                            {
                                                object childObjectToSet = sameTableElementInfo.GetMemberValue(objectToSet);
                                                if (childObjectToSet == null)
                                                {
                                                    childObjectToSet = Activator.CreateInstance(sameTableElementInfo.MemberType);
                                                }
                                                objectToSet = childObjectToSet;
                                            }
                                        }
                                        childRelation.SetMemberValue(objectToSet, itemToSet);
                                        anyInstanceFieldsWereSetMap[objectToSet] = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
#if REMOVE_EMPTY_OBJECTS
            if (list != null)
            {
                List <string> removeKeys = new List <string>();
                foreach (KeyValuePair <string, IList> pair in list)
                {
                    if (pair.Value != null)
                    {
                        for (int i = pair.Value.Count - 1; i >= 0; --i)
                        {
                            object checkObject = pair.Value[i];
                            if (!anyInstanceFieldsWereSetMap[checkObject])
                            {
                                pair.Value.RemoveAt(i);
                            }
                        }
                    }
                    if (CollectionUtils.IsNullOrEmpty(pair.Value))
                    {
                        removeKeys.Add(pair.Key);
                    }
                }
                foreach (string removeKey in removeKeys)
                {
                    list.Remove(removeKey);
                }
            }
#endif // REMOVE_EMPTY_OBJECTS

            return(CollectionUtils.IsNullOrEmpty(list) ? null : list);
        }
Example #11
0
 public virtual void SetSelectColumnValue <T>(T objectToSet, object value, ColumnCachedValues cachedValues)
 {
     base.SetMemberValue <T>(objectToSet, value);
 }
Example #12
0
 public override void SetSelectColumnValue <T>(T objectToSet, object value, ColumnCachedValues cachedValues)
 {
 }
Example #13
0
        public override object GetInsertColumnValue(object parentOfObjectToSet, object objectToSave, ColumnCachedValues cachedValues)
        {
            ExceptionUtils.ThrowIfNull(parentOfObjectToSet, "parentOfObjectToSave");

            object pkGuid;

            ExceptionUtils.ThrowIfFalse(cachedValues.ObjectToPrimaryKeyMap.TryGetValue(parentOfObjectToSet, out pkGuid), "Missing FK value");
            return(pkGuid);
        }
Example #14
0
 public override void SetSelectColumnValue <T>(T objectToSet, object value, ColumnCachedValues cachedValues)
 {
     cachedValues.ObjectToPrimaryKeyMap[objectToSet] = value;
 }
Example #15
0
        public override object GetInsertColumnValue(object parentOfObjectToSave, object objectToSave, ColumnCachedValues cachedValues)
        {
            object pkGuid;

            if (Utils.IsValidColumnType(objectToSave.GetType()))
            {
                // This is a virtual table for string[], int[], enum[], etc.
                pkGuid = StringUtils.CreateSequentialGuid();
            }
            else
            {
                if (!cachedValues.ObjectToPrimaryKeyMap.TryGetValue(objectToSave, out pkGuid))
                {
                    pkGuid = StringUtils.CreateSequentialGuid();
                    cachedValues.ObjectToPrimaryKeyMap[objectToSave] = pkGuid;
                }
                else
                {
                    DebugUtils.CheckDebuggerBreak();
                }
            }
            return(pkGuid);
        }
        protected virtual void SaveToDatabase(object parentOfObjectToSave, object objectToSave,
                                              Table tableOfObjectToSave, ColumnCachedValues cachedValues, MappingContext mappingContext,
                                              Dictionary <string, int> insertRowCounts, IDbCommand command)
        {
            if (objectToSave == null)
            {
                return;
            }

            Type objectToSaveType = objectToSave.GetType();

            if (tableOfObjectToSave == null)
            {
                tableOfObjectToSave = mappingContext.GetTableForType(objectToSaveType);
            }

            Table parentTable = null;

            if (parentOfObjectToSave != null)
            {
                parentTable = mappingContext.GetTableForType(parentOfObjectToSave.GetType());
            }

            if (tableOfObjectToSave.PopulateInsertValues(command, parentOfObjectToSave, parentTable, objectToSave, cachedValues))
            {
                DebugUtils.AssertDebuggerBreak(command.Parameters.Count == tableOfObjectToSave.AllColumns.Count);
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    DebugUtils.CheckDebuggerBreak();
                    throw;
                }
                if (insertRowCounts != null)
                {
                    int value;
                    if (insertRowCounts.TryGetValue(tableOfObjectToSave.TableName, out value))
                    {
                        value++;
                    }
                    else
                    {
                        value = 1;
                    }
                    insertRowCounts[tableOfObjectToSave.TableName] = value;
                }
            }
            // Save children
            if (tableOfObjectToSave.ChildRelationMembers != null)
            {
                try
                {
                    Dictionary <object, bool> alreadyProcessedMemberValues = new Dictionary <object, bool>(tableOfObjectToSave.ChildRelationMembers.Count);

                    foreach (ChildRelationInfo childRelation in tableOfObjectToSave.ChildRelationMembers)
                    {
                        object relationMember = objectToSave;
                        if (childRelation.ParentToMemberChain != null)
                        {
                            foreach (SameTableElementInfo sameTableElementInfo in childRelation.ParentToMemberChain)
                            {
                                relationMember = sameTableElementInfo.GetMemberValue(relationMember);
                                if (relationMember == null)
                                {
                                    break;
                                }
                            }
                        }

                        if (relationMember != null)
                        {
                            if (childRelation.IsOneToMany)
                            {
                                IEnumerable memberEnumerable = childRelation.GetMemberEnumerable(relationMember);
                                if (memberEnumerable != null)
                                {
                                    if (alreadyProcessedMemberValues.ContainsKey(memberEnumerable))
                                    {
                                        // This is for object[] members that may be mapped to multiple types
                                    }
                                    else
                                    {
                                        bool insertedAny = false;
                                        alreadyProcessedMemberValues[memberEnumerable] = true;
                                        Table elementTable = null;
                                        if (Utils.IsValidColumnType(childRelation.ValueType))
                                        {
                                            elementTable = childRelation.ChildTable;
                                        }
                                        foreach (object element in memberEnumerable)
                                        {
                                            if (element != null)
                                            {
                                                SaveToDatabase(objectToSave, element, elementTable, cachedValues, mappingContext,
                                                               insertRowCounts, command);
                                                insertedAny = true;
                                            }
                                        }
                                        if (!insertedAny)
                                        {
                                        }
                                    }
                                }
                            }
                            else // One to one
                            {
                                object element = childRelation.GetMemberValue(relationMember);
                                if (element != null)
                                {
                                    if (alreadyProcessedMemberValues.ContainsKey(element))
                                    {
                                        // This is for object members that may be mapped to multiple types
                                    }
                                    else
                                    {
                                        alreadyProcessedMemberValues[element] = true;
                                        Table elementTable = null;
                                        if (Utils.IsValidColumnType(childRelation.ValueType))
                                        {
                                            elementTable = childRelation.ChildTable;
                                        }
                                        if (element != null)
                                        {
                                            SaveToDatabase(objectToSave, element, elementTable, cachedValues, mappingContext,
                                                           insertRowCounts, command);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    DebugUtils.CheckDebuggerBreak();
                    throw;
                }
            }
        }
Example #17
0
        public virtual object GetInsertColumnValue(object parentOfObjectToSave, object objectToSave, ColumnCachedValues cachedValues)
        {
            object value = null;

            if (MemberInfo == null)
            {
                if (objectToSave != null)
                {
                    // This would be string, int, double, etc. virtual table
                    DebugUtils.AssertDebuggerBreak(Utils.IsValidColumnType(objectToSave.GetType()));
                    value = objectToSave;
                }
            }
            else
            {
                value = GetMemberValue(objectToSave);
            }
            if (value == null)
            {
                if (this.IsNullable)
                {
                    value = DBNull.Value;
                }
                else
                {
                    throw new MappingException("A column.MemberInfo \"{0}\" has a null value, but the column is specified as non-null: {1}",
                                               MemberInfo.ToString(), this.ToString());
                }
            }
            else if (m_IsDbBoolString)
            {
                value = ((bool)value) ? "Y" : "N";
            }
            else if (m_IsTenDigitDateString)
            {
                value = DateTime.Parse(value.ToString()).ToString("yyyy-MM-dd");
            }
            else if (m_IsTimeType)
            {
                if (m_MemberType == typeof(string))
                {
                    TimeSpan timeSpan = TimeSpan.Parse(value.ToString());
                    value = new DateTime(1900, 1, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
                }
                else
                {
                    DateTime existingValue = DateTime.Parse(value.ToString());
                    value = new DateTime(1900, 1, 1, existingValue.Hour, existingValue.Minute, existingValue.Second);
                }
            }
            else if ((m_ColumnType == DbType.DateTime) || (m_ColumnType == DbType.Date))
            {
                DateTime dateTime = DateTime.Parse(value.ToString());
                return(MakeValidDbDateTime(dateTime));
            }
            return(value);
        }