コード例 #1
0
        /// <summary>
        /// Construct an instance of the given type using data from the first row of the
        /// supplied SqlResult instance.
        /// Refer to the Construct method of the <see cref="ObjectMap"/> class for details.
        /// </summary>
        /// <param name="type">The type of object to construct</param>
        /// <param name="sr">The SqlResult instance holding the data</param>
        /// <param name="key">Additional fields not available in the result set (e.g. primary key fields)</param>
        /// <returns>An instance of the given type</returns>
        /// <exception cref="GentleException"> will be raised if no object could be created</exception>
        public static object GetInstance(Type type, SqlResult sr, Key key)
        {
            Check.Verify(sr != null && sr.ErrorCode == 0 && sr.RowsContained == 1,
                         Error.UnexpectedRowCount, sr.RowsContained, 1);
            ObjectMap objectMap = GetMap(sr.SessionBroker, type);

            // check for dynamic type
            if (objectMap.InheritanceMap != null)
            {
                string assemblyQualifiedName = sr.GetString(0, objectMap.InheritanceMap.ColumnName);
                type      = LoadType(assemblyQualifiedName);
                objectMap = GetMap(sr.SessionBroker, type);                   // update objectmap to actual type from database
            }
            // determine constructor
            object[] row = (object[])sr.Rows[0];
            int      columnComboHashCode = objectMap.DetermineConstructor(sr.ColumnNames, row);
            // create object
            object result = objectMap.Construct(columnComboHashCode, row, sr.SessionBroker);

            // check whether to store query result information
            if (GentleSettings.CacheObjects && GentleSettings.SkipQueryExecution &&
                objectMap.CacheStrategy != CacheStrategy.Never)
            {
                IList <string> results = new List <string> {
                    objectMap.GetInstanceHashKey(result)
                };
                CacheManager.Insert(sr.Statement.CacheKey, results);
            }
            // mark as persisted
            if (result is IEntity)
            {
                (result as IEntity).IsPersisted = true;
            }
            return(result);
        }
コード例 #2
0
        /// <summary>
        /// Construct a unique string a
        /// </summary>
        internal string GetRowHashKey(object[] row)
        {
            Hashtable values = new Hashtable();

            for (int i = 0; i < row.Length; i++)
            {
                if (columnPrimaryKeyMask[i])
                {
                    object rowValue = row[i] != null ? row[i].ToString() : "null";
                    values[columnInfo.Fields[i].MemberName] = rowValue;
                }
            }
            return(objectMap.GetInstanceHashKey(values));
        }
コード例 #3
0
        /// <summary>
        /// Internal helper method used for standard CRUD operations on known types.
        /// </summary>
        /// <param name="obj">The object instance being operated on</param>
        /// <param name="st">The statement type</param>
        /// <param name="conn">An existing database connection to reuse. This is useful
        /// when you need to execute statements in the same session as a previous statement.</param>
        /// <param name="tr">The database transaction for when participating in transactions.</param>
        /// <returns>The result of the operation</returns>
        internal SqlResult Execute(object obj, StatementType st, IDbConnection conn, IDbTransaction tr)
        {
            ObjectMap map = ObjectFactory.GetMap(this, obj);

            // perform validations first
            if (StatementType.Insert == st || StatementType.Update == st)
            {
                ValidationBroker.Validate(obj);
            }

            if (map.IsSoftDelete && st == StatementType.Delete)
            {
                st = StatementType.SoftDelete;
            }
            SqlStatement stmt = GetStatement(obj, st);

            stmt.SetParameters(obj, true);
            // connections are supplied from outside when in a transaction or executing batch queries
            conn = tr != null ? tr.Connection : conn ?? stmt.SessionBroker.Provider.GetConnection();
            SqlResult sr = stmt.Execute(conn, tr);

            // throw an error if execution failed
            Check.Verify(sr.ErrorCode == 0, Error.StatementError, sr.Error, stmt.Sql);
            // check that statement affected a row
            if (st == StatementType.Insert || st == StatementType.Update ||
                st == StatementType.Delete || st == StatementType.SoftDelete)
            {
                Check.Verify(sr.RowsAffected >= 1, Error.UnexpectedRowCount, sr.RowsAffected, "1+");
            }
            // update identity values for inserts
            if (st == StatementType.Insert)
            {
                if (sr.LastRowId != 0 && map.IdentityMap != null)
                {
                    map.SetIdentity(obj, sr.LastRowId);
                }
                if (obj is IEntity)
                {
                    (obj as IEntity).IsPersisted = true;
                }
                // this is not really necessary but nice for error checking (also used in test cases)
                if (map.InheritanceMap != null)
                {
                    map.InheritanceMap.SetValue(obj, obj.GetType().AssemblyQualifiedName);
                }
            }
            // update/invalidate the cache
            if (GentleSettings.CacheObjects && map.CacheStrategy != CacheStrategy.Never)
            {
                if (st == StatementType.Insert)
                {
                    // insert new object into cache
                    CacheManager.Insert(map.GetInstanceHashKey(obj), obj, map.CacheStrategy);
                    // invalidate query results for select statements for this type, reducing the
                    // effectiveness of the cache (but ensuring correct results)
                    if (GentleSettings.CacheStatements)
                    {
                        CacheManager.ClearQueryResultsByType(map.Type);
                    }
                }
                else if (st == StatementType.Delete || st == StatementType.SoftDelete)
                {
                    // remove invalidated object from the cache
                    CacheManager.Remove(obj);
                    // invalidate query results for select statements for this type, reducing the
                    // effectiveness of the cache (but ensuring correct results)
                    if (GentleSettings.CacheStatements)
                    {
                        CacheManager.ClearQueryResultsByType(map.Type);
                    }
                }
            }
            // update the in-memory version/revision counter for objects under concurrency control
            if (st == StatementType.Update && GentleSettings.ConcurrencyControl)
            {
                if (map.ConcurrencyMap != null)
                {
                    FieldMap fm      = map.ConcurrencyMap;
                    long     version = Convert.ToInt64(fm.GetValue(obj));
                    // handle wrap-around of the version counter
                    if ((fm.Type.Equals(typeof(int)) && version == int.MaxValue) ||
                        (fm.Type.Equals(typeof(long)) && version == long.MaxValue))
                    {
                        version = 1;
                    }
                    else
                    {
                        version += 1;
                    }
                    map.ConcurrencyMap.SetValue(obj, version);
                }
            }
            // update object with database-created values if UpdateAfterWrite is set to true
            if (map.IsUpdateAfterWrite && (st == StatementType.Insert || st == StatementType.Update))
            {
                if (tr != null)
                {
                    Refresh(obj, tr);
                }
                else
                {
                    Refresh(obj);
                }
            }
            return(sr);
        }
コード例 #4
0
        /// <summary>
        /// Construct multiple objects of a given type from the data contained in the given SqlResult
        /// object. Refer to the Construct method of the <see cref="ObjectMap"/> class for details.
        /// </summary>
        /// <param name="type">The type of object to construct</param>
        /// <param name="sr">The SqlResult instance holding the data</param>
        /// <param name="result">An optional existing container in which to store the created objects. If
        /// this parameter is null a new IList instance will be created.</param>
        /// <returns>An IList holding the created objects</returns>
        /// <exception cref="GentleException"> will be raised if no object could be created</exception>
        public static IList GetCollection(Type type, SqlResult sr, IList result)
        {
            if (result == null)
            {
                result = MakeGenericList(type);
            }
            ObjectMap objectMap = GetMap(sr.SessionBroker, type);
            // check whether to store query result information
            bool isCache = GentleSettings.CacheObjects && GentleSettings.SkipQueryExecution &&
                           objectMap.CacheStrategy != CacheStrategy.Never;
            IList cache = isCache ? new ArrayList() : null;

            // remember keys of cached objects to permit SQE
            // process result set
            if (sr.RowsContained > 0)
            {
                ObjectMap actualMap           = objectMap;
                int       columnComboHashCode = 0;
                // cache constructor info for dynamic type construction
                Hashtable typeHash = null;
                Hashtable typeMaps = null;
                if (objectMap.InheritanceMap != null)
                {
                    typeHash = new Hashtable();
                    typeMaps = new Hashtable();
                }
                else                 // precompute fixed hash
                {
                    columnComboHashCode = objectMap.DetermineConstructor(sr.ColumnNames, (object[])sr.Rows[0]);
                }
                // process result set
                for (int i = 0; i < sr.Rows.Count; i++)
                {
                    object[] row = (object[])sr.Rows[i];
                    // dynamic object construction handling
                    if (typeHash != null)
                    {
                        string assemblyQualifiedName = sr.GetString(i, objectMap.InheritanceMap.ColumnName);
                        if (typeHash.ContainsKey(assemblyQualifiedName))
                        {
                            columnComboHashCode = (int)typeHash[assemblyQualifiedName];
                            actualMap           = (ObjectMap)typeMaps[assemblyQualifiedName];
                        }
                        else
                        {
                            Type rowType = LoadType(assemblyQualifiedName);
                            actualMap                       = GetMap(sr.SessionBroker, rowType);
                            columnComboHashCode             = actualMap.DetermineConstructor(sr.ColumnNames, (object[])sr.Rows[0]);
                            typeMaps[assemblyQualifiedName] = actualMap;
                            typeHash[assemblyQualifiedName] = columnComboHashCode;
                        }
                    }
                    // skip non-derived classes for dynamic types
                    if (actualMap.Type == objectMap.Type || actualMap.Type.IsSubclassOf(objectMap.Type))
                    {
                        object obj = actualMap.Construct(columnComboHashCode, row, sr.SessionBroker);
                        if (obj is IEntity)
                        {
                            (obj as IEntity).IsPersisted = true;
                        }
                        result.Add(obj);
                        // cache result if necessary
                        if (isCache)
                        {
                            cache.Add(actualMap.GetInstanceHashKey(obj));
                        }
                    }
                }
            }
            if (isCache)
            {
                CacheManager.Insert(sr.Statement.CacheKey, cache);
            }
            return(result);
        }