internal ObjectResult <TResultType> Execute <TResultType>(ObjectContext context, ObjectParameterCollection parameterValues)
        {
            DbDataReader storeReader = null;

            try
            {
                // create entity command (just do this to snarf store command)
                EntityCommandDefinition commandDefinition = (EntityCommandDefinition)this.CommandDefinition;
                EntityCommand           entityCommand     = new EntityCommand((EntityConnection)context.Connection, commandDefinition);

                // pass through parameters and timeout values
                if (context.CommandTimeout.HasValue)
                {
                    entityCommand.CommandTimeout = context.CommandTimeout.Value;
                }

                if (parameterValues != null)
                {
                    foreach (ObjectParameter parameter in parameterValues)
                    {
                        int index = entityCommand.Parameters.IndexOf(parameter.Name);

                        if (index != -1)
                        {
                            entityCommand.Parameters[index].Value = parameter.Value ?? DBNull.Value;
                        }
                    }
                }

                // acquire store reader
                storeReader = commandDefinition.ExecuteStoreCommands(entityCommand, CommandBehavior.Default);

                ShaperFactory <TResultType> shaperFactory = (ShaperFactory <TResultType>) this.ResultShaperFactory;
                Shaper <TResultType>        shaper        = shaperFactory.Create(storeReader, context, context.MetadataWorkspace, this.MergeOption, true);

                // create materializer delegate
                TypeUsage resultItemEdmType;

                if (ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType)
                {
                    resultItemEdmType = ((CollectionType)ResultType.EdmType).TypeUsage;
                }
                else
                {
                    resultItemEdmType = ResultType;
                }

                return(new ObjectResult <TResultType>(shaper, this._singleEntitySet, resultItemEdmType));
            }
            catch (Exception)
            {
                if (null != storeReader)
                {
                    // Note: The caller is responsible for disposing reader if creating
                    // the enumerator fails.
                    storeReader.Dispose();
                }
                throw;
            }
        }
Exemple #2
0
        private EntityCommand PrepareEntityCommand(
            ObjectContext context,
            ObjectParameterCollection parameterValues)
        {
            EntityCommandDefinition commandDefinition = (EntityCommandDefinition)this.CommandDefinition;
            EntityConnection        connection        = (EntityConnection)context.Connection;
            EntityCommand           entityCommand     = new EntityCommand(connection, commandDefinition, context.InterceptionContext, (EntityCommand.EntityDataReaderFactory)null);

            if (context.CommandTimeout.HasValue)
            {
                entityCommand.CommandTimeout = context.CommandTimeout.Value;
            }
            if (parameterValues != null)
            {
                foreach (ObjectParameter parameterValue in parameterValues)
                {
                    int index = entityCommand.Parameters.IndexOf(parameterValue.Name);
                    if (index != -1)
                    {
                        entityCommand.Parameters[index].Value = parameterValue.Value ?? (object)DBNull.Value;
                    }
                }
            }
            if (connection.CurrentTransaction != null)
            {
                entityCommand.Transaction = connection.CurrentTransaction;
            }
            return(entityCommand);
        }
Exemple #3
0
 private void InnerPrepare()
 {
     if (this._parameters.IsDirty)
     {
         this.Unprepare();
     }
     this._commandDefinition = this.GetCommandDefinition();
 }
Exemple #4
0
        // <summary>
        // Clear out any "compile" state
        // </summary>
        internal virtual void Unprepare()
        {
            _commandDefinition   = null;
            _preparedCommandTree = null;

            // Clear the dirty flag on the parameters and parameter collection
            _parameters.ResetIsDirty();
        }
Exemple #5
0
 internal EntityCommand(
     EntityConnection connection,
     EntityCommandDefinition entityCommandDefinition,
     DbInterceptionContext context,
     EntityCommand.EntityDataReaderFactory factory = null)
     : this(entityCommandDefinition, context, factory)
 {
     this._connection = connection;
 }
Exemple #6
0
        internal string ToTraceString()
        {
            EntityCommandDefinition commandDefinition = this.CommandDefinition as EntityCommandDefinition;

            if (commandDefinition == null)
            {
                return(string.Empty);
            }
            return(commandDefinition.ToTraceString());
        }
Exemple #7
0
        // <summary>
        // Creates a prepared version of this command without regard to the current connection state.
        // Called by both <see cref="Prepare" /> and <see cref="ToTraceString" />.
        // </summary>
        private void InnerPrepare()
        {
            // Unprepare if the parameters have changed to force a reprepare
            if (_parameters.IsDirty)
            {
                Unprepare();
            }

            _commandDefinition = GetCommandDefinition();
            Debug.Assert(null != _commandDefinition, "_commandDefinition cannot be null");
        }
        internal string ToTraceString()
        {
            string traceString = string.Empty;
            EntityCommandDefinition entityCommandDef = this.CommandDefinition as EntityCommandDefinition;

            if (entityCommandDef != null)
            {
                traceString = entityCommandDef.ToTraceString();
            }
            return(traceString);
        }
Exemple #9
0
        private static IList <RowType> GetMappedCommandReturnTypes(ObjectQueryExecutionPlan plan)
        {
            EntityCommandDefinition command = plan.CommandDefinition as EntityCommandDefinition;

            if (command == null)
            {
                return(null);
            }

            return(command.MappedCommandReturnTypes);
        }
Exemple #10
0
        public virtual string ToTraceString()
        {
            this.CheckConnectionPresent();
            this.InnerPrepare();
            EntityCommandDefinition commandDefinition = this._commandDefinition;

            if (commandDefinition != null)
            {
                return(commandDefinition.ToTraceString());
            }
            return(string.Empty);
        }
Exemple #11
0
        internal virtual EntityCommandDefinition GetCommandDefinition()
        {
            EntityCommandDefinition entityCommandDefinition = this._commandDefinition;

            if (entityCommandDefinition == null)
            {
                if (!this.TryGetEntityCommandDefinitionFromQueryCache(out entityCommandDefinition))
                {
                    entityCommandDefinition = this.CreateCommandDefinition();
                }
                this._commandDefinition = entityCommandDefinition;
            }
            return(entityCommandDefinition);
        }
Exemple #12
0
 internal EntityCommand(
     EntityCommandDefinition commandDefinition,
     DbInterceptionContext context,
     EntityCommand.EntityDataReaderFactory factory = null)
     : this(context, factory)
 {
     this._commandDefinition = commandDefinition;
     this._parameters        = new EntityParameterCollection();
     foreach (EntityParameter parameter in commandDefinition.Parameters)
     {
         this._parameters.Add(parameter.Clone());
     }
     this._parameters.ResetIsDirty();
     this._isCommandDefinitionBased = true;
 }
        public virtual ObjectQueryExecutionPlan Prepare(
            ObjectContext context,
            DbQueryCommandTree tree,
            Type elementType,
            MergeOption mergeOption,
            bool streaming,
            Span span,
            IEnumerable <Tuple <ObjectParameter, QueryParameterExpression> > compiledQueryParameters,
            AliasGenerator aliasGenerator)
        {
            TypeUsage    resultType = tree.Query.ResultType;
            DbExpression newQuery;
            SpanIndex    spanInfo;

            if (ObjectSpanRewriter.TryRewrite(tree, span, mergeOption, aliasGenerator, out newQuery, out spanInfo))
            {
                tree = DbQueryCommandTree.FromValidExpression(tree.MetadataWorkspace, tree.DataSpace, newQuery, tree.UseDatabaseNullSemantics);
            }
            else
            {
                spanInfo = (SpanIndex)null;
            }
            EntityCommandDefinition commandDefinition   = ObjectQueryExecutionPlanFactory.CreateCommandDefinition(context, tree);
            ShaperFactory           resultShaperFactory = System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap(this._translator, elementType, commandDefinition.CreateColumnMap((DbDataReader)null), context.MetadataWorkspace, spanInfo, mergeOption, streaming, false);
            EntitySet singleEntitySet = (EntitySet)null;

            if (resultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType && commandDefinition.EntitySets != null)
            {
                foreach (EntitySet entitySet in commandDefinition.EntitySets)
                {
                    if (entitySet != null && entitySet.ElementType.IsAssignableFrom(((CollectionType)resultType.EdmType).TypeUsage.EdmType))
                    {
                        if (singleEntitySet == null)
                        {
                            singleEntitySet = entitySet;
                        }
                        else
                        {
                            singleEntitySet = (EntitySet)null;
                            break;
                        }
                    }
                }
            }
            return(new ObjectQueryExecutionPlan((DbCommandDefinition)commandDefinition, resultShaperFactory, resultType, mergeOption, streaming, singleEntitySet, compiledQueryParameters));
        }
Exemple #14
0
        // Return the execution's column list in column position order.
        private static IDictionary <string, int> GetColumnNamePositionMap(ObjectQueryExecutionPlan plan)
        {
            EntityCommandDefinition command = plan.CommandDefinition as EntityCommandDefinition;

            if (command == null)
            {
                return(null);
            }

            var columnMap = command.CreateColumnMap(null) as SimpleCollectionColumnMap;

            if (columnMap == null)
            {
                return(null);
            }

            var element = columnMap.Element as RecordColumnMap;

            if (element == null)
            {
                return(null);
            }

            var properties = element.Properties;

            if (properties == null)
            {
                return(null);
            }

            var columnsPosNameMap = new Dictionary <string, int>();

            foreach (var property in properties)
            {
                var scalarProperty = property as ScalarColumnMap;

                if (scalarProperty == null)
                {
                    return(null);
                }

                columnsPosNameMap[scalarProperty.Name] = scalarProperty.ColumnPos;
            }

            return(columnsPosNameMap);
        }
Exemple #15
0
        // <summary>
        // Get the command definition for the command; will construct one if there is not already
        // one constructed, which means it will prepare the command on the client.
        // </summary>
        // <returns> the command definition </returns>
        internal virtual EntityCommandDefinition GetCommandDefinition()
        {
            var entityCommandDefinition = _commandDefinition;

            // Construct the command definition using no special options;
            if (null == entityCommandDefinition)
            {
                // check if the _commandDefinition is in cache
                if (!TryGetEntityCommandDefinitionFromQueryCache(out entityCommandDefinition))
                {
                    // if not, construct the command definition using no special options;
                    entityCommandDefinition = CreateCommandDefinition();
                }

                _commandDefinition = entityCommandDefinition;
            }

            return(entityCommandDefinition);
        }
Exemple #16
0
        // <summary>
        // Internal constructor used by EntityCommandDefinition
        // </summary>
        // <param name="commandDefinition"> The prepared command definition that can be executed using this EntityCommand </param>
        internal EntityCommand(EntityCommandDefinition commandDefinition, DbInterceptionContext context, EntityDataReaderFactory factory = null)
            : this(context, factory)
        {
            // Assign other member fields from the parameters
            _commandDefinition = commandDefinition;
            _parameters        = new EntityParameterCollection();

            // Make copies of the parameters
            foreach (var parameter in commandDefinition.Parameters)
            {
                _parameters.Add(parameter.Clone());
            }

            // Reset the dirty flag that was set to true when the parameters were added so that it won't say
            // it's dirty to start with
            _parameters.ResetIsDirty();

            // Track the fact that this command was created from and represents an already prepared command definition
            _isCommandDefinitionBased = true;
        }
Exemple #17
0
        private bool TryGetEntityCommandDefinitionFromQueryCache(
            out EntityCommandDefinition entityCommandDefinition)
        {
            entityCommandDefinition = (EntityCommandDefinition)null;
            if (!this._enableQueryPlanCaching || string.IsNullOrEmpty(this._esqlCommandText))
            {
                return(false);
            }
            EntityClientCacheKey key = new EntityClientCacheKey(this);
            QueryCacheManager    queryCacheManager = this._connection.GetMetadataWorkspace().GetQueryCacheManager();

            if (!queryCacheManager.TryCacheLookup <EntityClientCacheKey, EntityCommandDefinition>(key, out entityCommandDefinition))
            {
                entityCommandDefinition = this.CreateCommandDefinition();
                QueryCacheEntry outQueryCacheEntry = (QueryCacheEntry)null;
                if (queryCacheManager.TryLookupAndAdd(new QueryCacheEntry((QueryCacheKey)key, (object)entityCommandDefinition), out outQueryCacheEntry))
                {
                    entityCommandDefinition = (EntityCommandDefinition)outQueryCacheEntry.GetTarget();
                }
            }
            return(true);
        }
Exemple #18
0
        // <summary>
        // Gets an entitycommanddefinition from cache if a match is found for the given cache key.
        // </summary>
        // <param name="entityCommandDefinition"> out param. returns the entitycommanddefinition for a given cache key </param>
        // <returns> true if a match is found in cache, false otherwise </returns>
        private bool TryGetEntityCommandDefinitionFromQueryCache(out EntityCommandDefinition entityCommandDefinition)
        {
            Debug.Assert(null != _connection, "Connection must not be null at this point");
            entityCommandDefinition = null;

            // if EnableQueryCaching is false, then just return to force the CommandDefinition to be created
            if (!_enableQueryPlanCaching ||
                string.IsNullOrEmpty(_esqlCommandText))
            {
                return(false);
            }

            // Create cache key
            var queryCacheKey = new EntityClientCacheKey(this);

            // Try cache lookup
            var queryCacheManager = _connection.GetMetadataWorkspace().GetQueryCacheManager();

            Debug.Assert(null != queryCacheManager, "QuerycacheManager instance cannot be null");
            if (!queryCacheManager.TryCacheLookup(queryCacheKey, out entityCommandDefinition))
            {
                // if not, construct the command definition using no special options;
                entityCommandDefinition = CreateCommandDefinition();

                // add to the cache
                QueryCacheEntry outQueryCacheEntry = null;
                if (queryCacheManager.TryLookupAndAdd(new QueryCacheEntry(queryCacheKey, entityCommandDefinition), out outQueryCacheEntry))
                {
                    entityCommandDefinition = (EntityCommandDefinition)outQueryCacheEntry.GetTarget();
                }
            }

            Debug.Assert(null != entityCommandDefinition, "out entityCommandDefinition must not be null");

            return(true);
        }
 /// <summary>
 /// Constructs a new EntityCommand given a EntityConnection and an EntityCommandDefition. This 
 /// constructor is used by ObjectQueryExecution plan to execute an ObjectQuery.
 /// </summary>
 /// <param name="connection">The connection against which this EntityCommand should execute</param>
 /// <param name="commandDefinition">The prepared command definition that can be executed using this EntityCommand</param>
 internal EntityCommand(
     EntityConnection connection, EntityCommandDefinition entityCommandDefinition, EntityDataReaderFactory factory = null)
     : this(entityCommandDefinition, factory)
 {
     _connection = connection;
 }
Exemple #20
0
 internal virtual void Unprepare()
 {
     this._commandDefinition   = (EntityCommandDefinition)null;
     this._preparedCommandTree = (DbCommandTree)null;
     this._parameters.ResetIsDirty();
 }
        /// <summary>
        /// Get the command definition for the command; will construct one if there is not already
        /// one constructed, which means it will prepare the command on the client.
        /// </summary>
        /// <returns>the command definition</returns>
        internal virtual EntityCommandDefinition GetCommandDefinition()
        {
            var entityCommandDefinition = _commandDefinition;

            // Construct the command definition using no special options;
            if (null == entityCommandDefinition)
            {
                // check if the _commandDefinition is in cache
                if (!TryGetEntityCommandDefinitionFromQueryCache(out entityCommandDefinition))
                {
                    // if not, construct the command definition using no special options;
                    entityCommandDefinition = CreateCommandDefinition();
                }

                _commandDefinition = entityCommandDefinition;
            }

            return entityCommandDefinition;
        }
        /// <summary>
        /// Gets an entitycommanddefinition from cache if a match is found for the given cache key.
        /// </summary>
        /// <param name="entityCommandDefinition">out param. returns the entitycommanddefinition for a given cache key</param>
        /// <returns>true if a match is found in cache, false otherwise</returns>
        private bool TryGetEntityCommandDefinitionFromQueryCache(out EntityCommandDefinition entityCommandDefinition)
        {
            Debug.Assert(null != _connection, "Connection must not be null at this point");
            entityCommandDefinition = null;

            // if EnableQueryCaching is false, then just return to force the CommandDefinition to be created
            if (!_enableQueryPlanCaching
                || string.IsNullOrEmpty(_esqlCommandText))
            {
                return false;
            }

            // Create cache key
            var queryCacheKey = new EntityClientCacheKey(this);

            // Try cache lookup
            var queryCacheManager = _connection.GetMetadataWorkspace().GetQueryCacheManager();
            Debug.Assert(null != queryCacheManager, "QuerycacheManager instance cannot be null");
            if (!queryCacheManager.TryCacheLookup(queryCacheKey, out entityCommandDefinition))
            {
                // if not, construct the command definition using no special options;
                entityCommandDefinition = CreateCommandDefinition();

                // add to the cache
                QueryCacheEntry outQueryCacheEntry = null;
                if (queryCacheManager.TryLookupAndAdd(new QueryCacheEntry(queryCacheKey, entityCommandDefinition), out outQueryCacheEntry))
                {
                    entityCommandDefinition = (EntityCommandDefinition)outQueryCacheEntry.GetTarget();
                }
            }

            Debug.Assert(null != entityCommandDefinition, "out entityCommandDefinition must not be null");

            return true;
        }
        /// <summary>
        /// Internal constructor used by EntityCommandDefinition
        /// </summary>
        /// <param name="commandDefinition">The prepared command definition that can be executed using this EntityCommand</param>
        internal EntityCommand(EntityCommandDefinition commandDefinition, EntityDataReaderFactory factory = null)
            : this(factory)
        {
            // Assign other member fields from the parameters
            _commandDefinition = commandDefinition;
            _parameters = new EntityParameterCollection();

            // Make copies of the parameters
            foreach (var parameter in commandDefinition.Parameters)
            {
                _parameters.Add(parameter.Clone());
            }

            // Reset the dirty flag that was set to true when the parameters were added so that it won't say
            // it's dirty to start with
            _parameters.ResetIsDirty();

            // Track the fact that this command was created from and represents an already prepared command definition
            _isCommandDefinitionBased = true;
        }
        /// <summary>
        /// Clear out any "compile" state
        /// </summary>
        internal virtual void Unprepare()
        {
            _commandDefinition = null;
            _preparedCommandTree = null;

            // Clear the dirty flag on the parameters and parameter collection
            _parameters.ResetIsDirty();
        }
        /// <summary>
        /// Creates a prepared version of this command without regard to the current connection state.
        /// Called by both <see cref="Prepare"/> and <see cref="ToTraceString"/>.
        /// </summary>
        private void InnerPrepare()
        {
            // Unprepare if the parameters have changed to force a reprepare
            if (_parameters.IsDirty)
            {
                Unprepare();
            }

            _commandDefinition = GetCommandDefinition();
            Debug.Assert(null != _commandDefinition, "_commandDefinition cannot be null");
        }
        internal static ObjectQueryExecutionPlan Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Span span, CompiledQueryParameters compiledQueryParameters, AliasGenerator aliasGenerator)
        {
            TypeUsage treeResultType = tree.Query.ResultType;

            // Rewrite this tree for Span?
            DbExpression spannedQuery = null;
            SpanIndex    spanInfo;

            if (ObjectSpanRewriter.TryRewrite(tree, span, mergeOption, aliasGenerator, out spannedQuery, out spanInfo))
            {
                tree = DbQueryCommandTree.FromValidExpression(tree.MetadataWorkspace, tree.DataSpace, spannedQuery);
            }
            else
            {
                spanInfo = null;
            }

            DbConnection        connection = context.Connection;
            DbCommandDefinition definition = null;

            // The connection is required to get to the CommandDefinition builder.
            if (connection == null)
            {
                throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectQuery_InvalidConnection);
            }

            DbProviderServices services = DbProviderServices.GetProviderServices(connection);

            try
            {
                definition = services.CreateCommandDefinition(tree);
            }
            catch (EntityCommandCompilationException)
            {
                // If we're running against EntityCommand, we probably already caught the providers'
                // exception and wrapped it, we don't want to do that again, so we'll just rethrow
                // here instead.
                throw;
            }
            catch (Exception e)
            {
                // we should not be wrapping all exceptions
                if (EntityUtil.IsCatchableExceptionType(e))
                {
                    // we don't wan't folks to have to know all the various types of exceptions that can
                    // occur, so we just rethrow a CommandDefinitionException and make whatever we caught
                    // the inner exception of it.
                    throw EntityUtil.CommandCompilation(System.Data.Entity.Strings.EntityClient_CommandDefinitionPreparationFailed, e);
                }
                throw;
            }

            if (definition == null)
            {
                throw EntityUtil.ProviderDoesNotSupportCommandTrees();
            }

            EntityCommandDefinition entityDefinition = (EntityCommandDefinition)definition;
            QueryCacheManager       cacheManager     = context.Perspective.MetadataWorkspace.GetQueryCacheManager();

            ShaperFactory shaperFactory = ShaperFactory.Create(elementType, cacheManager, entityDefinition.CreateColumnMap(null),
                                                               context.MetadataWorkspace, spanInfo, mergeOption, false);

            // attempt to determine entity information for this query (e.g. which entity type and which entity set)
            //EntityType rootEntityType = null;

            EntitySet singleEntitySet = null;

            if (treeResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType)
            {
                // determine if the entity set is unambiguous given the entity type
                if (null != entityDefinition.EntitySets)
                {
                    foreach (EntitySet entitySet in entityDefinition.EntitySets)
                    {
                        if (null != entitySet)
                        {
                            if (entitySet.ElementType.IsAssignableFrom(((CollectionType)treeResultType.EdmType).TypeUsage.EdmType))
                            {
                                if (singleEntitySet == null)
                                {
                                    // found a single match
                                    singleEntitySet = entitySet;
                                }
                                else
                                {
                                    // there's more than one matching entity set
                                    singleEntitySet = null;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(new ObjectQueryExecutionPlan(definition, shaperFactory, treeResultType, mergeOption, singleEntitySet, compiledQueryParameters));
        }
Exemple #27
0
 /// <summary>
 ///     Constructs a new EntityCommand given a EntityConnection and an EntityCommandDefition. This
 ///     constructor is used by ObjectQueryExecution plan to execute an ObjectQuery.
 /// </summary>
 /// <param name="connection"> The connection against which this EntityCommand should execute </param>
 /// <param name="commandDefinition"> The prepared command definition that can be executed using this EntityCommand </param>
 internal EntityCommand(
     EntityConnection connection, EntityCommandDefinition entityCommandDefinition, EntityDataReaderFactory factory = null)
     : this(entityCommandDefinition, factory)
 {
     _connection = connection;
 }