/// <summary>
        /// Materializes the results of the given command.
        /// </summary>
        /// <param name="command">Command to execute.</param>
        /// <param name="commandBehavior">Command behavior to use when executing the command.</param>
        /// <returns>Shaped results.</returns>
        public IEnumerable <T> Materialize(DbCommand command, CommandBehavior commandBehavior)
        {
            EnitityUtility.CheckArgumentNotNull(command, "command");

            using (command.Connection.CreateConnectionScope())
            {
                using (DbDataReader reader = command.ExecuteReader(commandBehavior))
                {
                    foreach (T element in this.Materialize(reader))
                    {
                        yield return(element);
                    }
                }
            }
        }
            public Expression OptimizeMethodCall(ReadOnlyCollection <string> fieldNames, ParameterExpression recordParameter, MethodCallExpression methodCall)
            {
                EnitityUtility.CheckArgumentNotNull(fieldNames, "fieldNames");
                EnitityUtility.CheckArgumentNotNull(methodCall, "methodCall");

                MethodPattern pattern = GetMethodPattern(methodCall);

                if (pattern == MethodPattern.Unsupported)
                {
                    // Cannot optimize this method.
                    return(methodCall);
                }

                // if the input record (arguments[0]) is not the record parameter, we cannot
                // leverage field names to optimize the shaper
                if (recordParameter != methodCall.Arguments[0])
                {
                    return(methodCall);
                }

                Expression ordinalExpression;

                if (!TryGetOrdinalExpression(fieldNames, methodCall, pattern, out ordinalExpression))
                {
                    return(methodCall);
                }

                Type returnType    = methodCall.Method.GetGenericArguments().Single();
                bool canAssignNull = returnType.IsClass || (returnType.IsGenericType && typeof(Nullable <>) == returnType.GetGenericTypeDefinition());

                // argument[0].GetValue(ordinal)
                Expression result = Expression.Call(methodCall.Arguments[0], s_getValue, ordinalExpression);

                if (canAssignNull)
                {
                    // (returnType)(argument[0].IsDBNull(ordinal) ? null : result)
                    result = Expression.Condition(
                        Expression.Call(methodCall.Arguments[0], s_isDBNull, ordinalExpression),
                        Expression.Constant(null, typeof(object)),
                        result);
                }

                // (returnType)result
                result = Expression.Convert(result, returnType);

                return(result);
            }
        /// <summary>
        /// Materializes rows in the given reader.
        /// </summary>
        /// <param name="reader">Results to materialize.</param>
        /// <returns>Shaped results.</returns>
        public IEnumerable <T> Materialize(DbDataReader reader)
        {
            EnitityUtility.CheckArgumentNotNull(reader, "reader");

            bool first = true;

            while (reader.Read())
            {
                if (first)
                {
                    InitializeShaper(reader);
                    first = false;
                }

                yield return(this.shaperDelegate(reader));
            }

            yield break;
        }
Exemple #4
0
        public static bool IsGenericAssignableFrom(this Type toType, Type fromType, out Type[] genericArguments)
        {
            EnitityUtility.CheckArgumentNotNull(toType, "toType");
            EnitityUtility.CheckArgumentNotNull(fromType, "fromType");

            if (!toType.IsGenericTypeDefinition ||
                fromType.IsGenericTypeDefinition)
            {
                // if 'toType' is not generic or 'fromType' is generic, the assignment pattern
                // is not matched (e.g. toType<genericArguments>.IsAssignableFrom(fromType)
                // cannot be satisfied)
                genericArguments = null;
                return(false);
            }

            if (toType.IsInterface)
            {
                // if the toType is an interface, simply look for the interface implementation in fromType
                foreach (Type interfaceCandidate in fromType.GetInterfaces())
                {
                    if (interfaceCandidate.IsGenericType && interfaceCandidate.GetGenericTypeDefinition() == toType)
                    {
                        genericArguments = interfaceCandidate.GetGenericArguments();
                        return(true);
                    }
                }
            }
            else
            {
                // if toType is not an interface, check hierarchy for match
                while (fromType != null)
                {
                    if (fromType.IsGenericType && fromType.GetGenericTypeDefinition() == toType)
                    {
                        genericArguments = fromType.GetGenericArguments();
                        return(true);
                    }
                    fromType = fromType.BaseType;
                }
            }
            genericArguments = null;
            return(false);
        }
Exemple #5
0
        /// <summary>
        /// Removes an entity from the EntitySet. The entity will be deleted
        /// when ObjectContext.SaveChanges is called.
        /// </summary>
        /// <param name="entity">Entity to delete.</param>
        public void DeleteOnSaveChanges(T entity)
        {
            EnitityUtility.CheckArgumentNotNull(((object)entity), "entity");

            // check that the entity actually exists first
            ObjectStateEntry stateEntry;

            if (!this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry))
            {
                //throw new ArgumentException(Messages.UntrackedEntity, "entity");
            }

            // now check that the entity belongs to the current entity set
            if (this.metadata != stateEntry.EntitySet)
            {
                //throw new ArgumentException(Messages.DeletingFromWrongSet, "entity");
            }

            this.Context.DeleteObject(entity);
        }
        /// <summary>
        /// Gets key value for a non-compound reference key (e.g. one foreign key component).
        /// </summary>
        /// <typeparam name="T">EntityReference element type</typeparam>
        /// <param name="entityReference">Entity reference.</param>
        /// <returns>Key value from entity reference.</returns>
        public static object GetKey <T>(this EntityReference <T> entityReference)
            where T : class, IEntityWithRelationships
        {
            EnitityUtility.CheckArgumentNotNull(entityReference, "entityReference");
            EntityKey entityKey = entityReference.EntityKey;

            if (null == entityKey)
            {
                if (entityReference.GetTargetEntitySet().ElementType.KeyMembers.Count != 1)
                {
                    //throw new InvalidOperationException(Messages.SimpleKeyOnly);
                }
                return(null);
            }
            var entityKeyValues = entityKey.EntityKeyValues;

            if (entityKeyValues.Length != 1)
            {
                //throw new InvalidOperationException(Messages.SimpleKeyOnly);
            }
            return(entityKeyValues[0].Value);
        }
        /// <summary>
        /// Gets a component of a key value for a (potentially compound) reference key.
        /// </summary>
        /// <typeparam name="T">EntityReference element type</typeparam>
        /// <param name="entityReference">Entity reference.</param>
        /// <param name="keyOrdinal">Index of the key component (with respect to the element type's
        /// EntityType.KeyMembers).</param>
        /// <returns>Key component value from entity reference.</returns>
        public static object GetKey <T>(this EntityReference <T> entityReference, int keyOrdinal)
            where T : class, IEntityWithRelationships
        {
            EnitityUtility.CheckArgumentNotNull(entityReference, "entityReference");
            if (keyOrdinal < 0)
            {
                throw new ArgumentOutOfRangeException("keyOrdinal");
            }
            EntityKey entityKey = entityReference.EntityKey;

            if (null == entityKey)
            {
                if (entityReference.GetTargetEntitySet().ElementType.KeyMembers.Count <= keyOrdinal)
                {
                    throw new ArgumentOutOfRangeException("keyOrdinal");
                }
                return(null);
            }
            if (entityKey.EntityKeyValues.Length <= keyOrdinal)
            {
                throw new ArgumentOutOfRangeException("keyOrdinal");
            }
            return(entityKey.EntityKeyValues[keyOrdinal].Value);
        }
        ///// <summary>
        ///// Creates a store command based on the connection used by given object context.
        ///// </summary>
        ///// <param name="context">Object context.</param>
        ///// <param name="commandText">Command text.</param>
        ///// <param name="parameters">Parameters to pass to the store command.</param>
        ///// <returns>Store command.</returns>
        //public static DbCommand CreateStoreCommand(ObjectContext context, string commandText, params object[] parameters)
        //{
        //    return CreateStoreCommand(context, commandText, CommandType.Text, parameters);
        //}

        /// <summary>
        /// Creates a store command based on the connection used by given object context.
        /// </summary>
        /// <param name="context">Object context.</param>
        /// <param name="commandText">Command text.</param>
        /// <param name="commandType">Command type.</param>
        /// <param name="parameters">Parameters to pass to the store command.</param>
        /// <returns>Store command.</returns>
        public static DbCommand CreateStoreCommand(ObjectContext context, string commandText, CommandType commandType, params object[] parameters)
        {
            EnitityUtility.CheckArgumentNotNull(context, "context");

            EntityConnection entityConnection = (EntityConnection)context.Connection;
            DbConnection     storeConnection  = entityConnection.StoreConnection;
            DbCommand        storeCommand     = storeConnection.CreateCommand();

            // setup command
            storeCommand.CommandText = commandText;
            storeCommand.CommandType = commandType;
            if (null != parameters)
            {
                storeCommand.Parameters.AddRange(parameters);
            }

            // pass through command timeout as appropriate
            if (context.CommandTimeout.HasValue)
            {
                storeCommand.CommandTimeout = context.CommandTimeout.Value;
            }

            return(storeCommand);
        }
Exemple #9
0
        /// <summary>
        /// Attaches an existing entity to the current entity set.
        /// </summary>
        /// <param name="entity">Entity to attach.</param>
        public void Attach(T entity)
        {
            EnitityUtility.CheckArgumentNotNull(((object)entity), "entity");

            this.Context.AttachTo(this.QualifiedEntitySetName, entity);
        }
Exemple #10
0
        /// <summary>
        /// Tracks a new entity for insertion when ObjectContext.SaveChanges is called.
        /// </summary>
        /// <param name="entity">Entity to insert.</param>
        public void InsertOnSaveChanges(T entity)
        {
            EnitityUtility.CheckArgumentNotNull(((object)entity), "entity");

            this.Context.AddObject(this.QualifiedEntitySetName, entity);
        }
        /// <summary>
        /// Expands all InvocationExpression instances within the given query.
        /// </summary>
        /// <param name="query">Query to expand.</param>
        /// <returns>Expanded query.</returns>
        public static IQueryable <TElement> ExpandInvocations <TElement>(this IQueryable <TElement> query)
        {
            EnitityUtility.CheckArgumentNotNull(query, "query");

            return(query.Provider.CreateQuery <TElement>(query.Expression.ExpandInvocations()));
        }
        /// <summary>
        /// Returns a handle on an IDisposable that can be used to safely control the lifetime
        /// of an open connection. If the connection is closed, it will be opened immediately
        /// and closed when the result of this method (the scope) is disposed. If the connection is already
        /// open, it remains open.
        /// <code>
        /// // Example with CreateConnectionScope
        /// using (command.Connection.CreateConnectionScope())
        /// {
        ///     command.ExecuteNonQuery();
        /// }
        ///
        /// // Example without
        /// bool connectionOpened = command.Connection.State == ConnectionState.Closed;
        /// if (connectionOpened)
        /// {
        ///     command.Connection.Open();
        /// }
        /// try
        /// {
        ///     command.ExecuteNonQuery();
        /// }
        /// finally
        /// {
        ///     if (connectionOpened &amp;&amp; command.Connection.State == ConnectionState.Open)
        ///     {
        ///         command.Connection.Close();
        ///     }
        /// }
        /// </code>
        /// </summary>
        /// <param name="connection">Connection to open.</param>
        /// <returns>Scope closing the connection on dispose.</returns>
        public static IDisposable CreateConnectionScope(this DbConnection connection)
        {
            EnitityUtility.CheckArgumentNotNull(connection, "connection");

            return(new OpenConnectionLifetime(connection));
        }