/// <summary> /// Selects a record of the specified type from a partitioned table in the database by its id and timestamp. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="id"></param> /// <param name="timestamp"></param> /// <returns></returns> public static object Get(Type type, ISession session, object id, object partitionKey, bool forUpdate = false) { // Make sure the mappings have been loaded for this type. LoadMappings(type); try { TableMapping mapping = _mappings[type]; // If caching is enabled for this entity type, check if it is in cache already. if (mapping.CachingEnabled && SessionFactory.CachingEnabled) { object cachedEntity = GetCachedEntity(type, id); if (cachedEntity != null) { return(cachedEntity); } } // Make sure that the table is not partitioned. if (mapping.IsPartitioned && partitionKey == null) { throw new Exception("Cannot select an object from a partitioned table without a partition key."); } //SqlCommand selectCommand = new SqlCommand(mapping.GetExpression, (SqlConnection)session.Connection); IDbCommand selectCommand = session.Connection.CreateCommand(); selectCommand.CommandText = mapping.GetExpression; if (forUpdate) { selectCommand.CommandText = String.Concat(selectCommand.CommandText, " FOR UPDATE"); } // Get the primary key column(s). List <ColumnMapping> idColumns = mapping.Columns.Where(c => c.IsPk).ToList(); // Check if we have multiple PKs or just one. if (idColumns.Count == 1) { AddParameter(selectCommand, "p_id0", idColumns[0].DbType, id); } else { int i = 0; // If we have multiple PKs then add a parameter for each of them. foreach (ColumnMapping idColumn in idColumns) { AddParameter(selectCommand, String.Format("p_id{0}", i++), idColumn.DbType, idColumn.PropertyInfo.GetValue(id, null)); } } // Add the partition key timestamp parameter. if (mapping.IsPartitioned) { ColumnMapping idColumn = mapping.Columns.FirstOrDefault(c => c.IsPartitionKey); AddParameter(selectCommand, "p_ts", idColumn.DbType, partitionKey); } LogCommand(selectCommand); object entity = null; using (IDataReader reader = selectCommand.ExecuteReader()) { if (reader.Read()) { entity = FromDb(type, reader); } } return(entity); } catch (Exception ex) { Log.Error("DataMapper.Get threw an exception.", ex); } return(null); }
/// <summary> /// Gets the database session key for the specified entity type. /// </summary> /// <param name="entityType"></param> /// <returns></returns> internal static string GetSessionKey(Type entityType) { TableMapping mapping = DataMapper.GetTableMapping(entityType); return((mapping == null) ? null : mapping.Key); }