Ejemplo n.º 1
0
        /// <summary>
        /// Foreach element in the input, runs the specified action. Yields input elements.
        /// </summary>
        /// <typeparam name="TResult">Element type.</typeparam>
        /// <param name="source">Source sequence.</param>
        /// <param name="action">Action to perform on each element of the source.</param>
        /// <returns>Source elements.</returns>
        public static IEnumerable <TResult> ForEach <TResult>(this IEnumerable <TResult> source, Action <TResult> action)
        {
            EnitityUtility.CheckArgumentNotNull(source, "source");
            EnitityUtility.CheckArgumentNotNull(action, "action");

            return(ForEachIterator(source, action));
        }
        public static T Field <T>(this IDataRecord record, string name)
        {
            EnitityUtility.CheckArgumentNotNull(record, "record");
            EnitityUtility.CheckArgumentNotNull(name, "name");

            return(Field <T>(record, record.GetOrdinal(name)));
        }
Ejemplo n.º 3
0
        private static EntitySet GetEntitySet(ObjectContext context, string containerName, string entitySetName)
        {
            EnitityUtility.CheckArgumentNotNull(context, "context");

            // if no container is specified, use the default for the context
            containerName = string.IsNullOrEmpty(containerName) ? context.DefaultContainerName : containerName;
            EnitityUtility.CheckArgumentNotNullOrEmpty(containerName, "containerName");

            // ensure the entity container exists
            EntityContainer container;

            if (!context.MetadataWorkspace.TryGetEntityContainer(containerName,
                                                                 DataSpace.CSpace, out container))
            {
                //throw new ArgumentException(String.Format(Messages.Culture, Messages.UnknownEntityContainer, containerName), "containerName");
            }

            EntitySet entitySet;

            if (string.IsNullOrEmpty(entitySetName))
            {
                // if no entity set is specified, try to find a single entity set taking this type
                entitySet = GetDefaultEntitySet(context, container);
            }
            else if (!container.TryGetEntitySetByName(entitySetName, false, out entitySet))
            {
                // ensure the requested entity set exists
                //throw new ArgumentException(String.Format(Messages.Culture, Messages.UnknownEntitySet, entitySetName), "entitySetName");
            }

            return(entitySet);
        }
        public static T Field <T>(this IDataRecord record, int ordinal)
        {
            EnitityUtility.CheckArgumentNotNull(record, "record");

            object value = record.IsDBNull(ordinal) ? null : record.GetValue(ordinal);

            return((T)value);
        }
        /// <summary>
        /// Associates results in the given source with an entity set. This supports tracking
        /// results in the state manager. If an existing element with the same key exists, it
        /// is returned instead.
        /// </summary>
        /// <typeparam name="TEntity">Entity type.</typeparam>
        /// <typeparam name="TBase">Base type for entity set.</typeparam>
        /// <param name="source">Entities to bind.</param>
        /// <param name="entitySet">Entity set to which elements should be bound.</param>
        /// <returns>Bound entities.</returns>
        public static IEnumerable <TEntity> Bind <TEntity, TBase>(this IEnumerable <TEntity> source, EntitySet <TBase> entitySet)
            where TEntity : TBase
        {
            EnitityUtility.CheckArgumentNotNull(source, "source");
            EnitityUtility.CheckArgumentNotNull(entitySet, "entitySet");

            return(source.Select(e => entitySet.FindOrAttach(e)));
        }
Ejemplo n.º 6
0
            internal static Expression <Func <IDataRecord, T> > Optimize(ReadOnlyCollection <string> fieldNames, Expression <Func <IDataRecord, T> > shaper)
            {
                EnitityUtility.CheckArgumentNotNull(fieldNames, "fieldNames");
                EnitityUtility.CheckArgumentNotNull(shaper, "shaper");

                OptimizingExpressionVisitor visitor = new OptimizingExpressionVisitor(fieldNames, shaper.Parameters.Single());

                return((Expression <Func <IDataRecord, T> >)visitor.Visit(shaper));
            }
            private InvocationExpander(ParameterExpression parameter, Expression expansion, InvocationExpander previous)
            {
                EnitityUtility.CheckArgumentNotNull(parameter, "parameter");
                EnitityUtility.CheckArgumentNotNull(expansion, "expansion");
                EnitityUtility.CheckArgumentNotNull(previous, "previous");

                _parameter = parameter;
                _expansion = expansion;
                _previous  = previous;
            }
Ejemplo n.º 8
0
        private static string GetCommandText(EntitySet entitySet)
        {
            EnitityUtility.CheckArgumentNotNull(entitySet, "entitySet");

            // to query an entity set, simply name it
            string containerName = entitySet.EntityContainer.Name;
            string entitySetName = entitySet.Name;

            // quote the identifiers
            return(QuoteIdentifier(containerName) + "." + QuoteIdentifier(entitySetName));
        }
        /// <summary>
        /// Sets reference key values.
        /// </summary>
        /// <typeparam name="T">EntityReference element type</typeparam>
        /// <param name="entityReference">Entity reference.</param>
        /// <param name="keyValues">Components of the key (aligned with the element type EntityType.KeyMembers)</param>
        public static void SetKey <T>(this EntityReference <T> entityReference, params object[] keyValues)
            where T : class, IEntityWithRelationships
        {
            EnitityUtility.CheckArgumentNotNull(entityReference, "entityReference");

            // if null keyValues given, clear the entity key
            if (null == keyValues)
            {
                entityReference.EntityKey = null;
            }

            IEnumerable <string> keyComponentNames;
            int    expectedKeyComponentCount;
            string entitySetName;

            if (null == entityReference.EntityKey)
            {
                // if there is no existing key, retrieve metadata through reflection
                EntitySet targetEntitySet = entityReference.GetTargetEntitySet();
                keyComponentNames         = targetEntitySet.ElementType.KeyMembers.Select(m => m.Name);
                expectedKeyComponentCount = targetEntitySet.ElementType.KeyMembers.Count;
                entitySetName             = targetEntitySet.EntityContainer.Name + "." + targetEntitySet.Name;
            }
            else
            {
                // if there is an existing key, just borrow its metadata
                EntityKey existingKey = entityReference.EntityKey;
                keyComponentNames         = existingKey.EntityKeyValues.Select(v => v.Key);
                expectedKeyComponentCount = existingKey.EntityKeyValues.Length;
                entitySetName             = existingKey.EntityContainerName + "." + existingKey.EntitySetName;
            }

            // check that the correct number of key values is given
            if (keyValues != null && expectedKeyComponentCount != keyValues.Length)
            {
                //throw new ArgumentException(Messages.UnexpectedKeyCount, "keyValues");
            }

            // check if there are any null key components (if so, the entire key is assumed
            // to be null)
            if (keyValues == null || keyValues.Any(v => null == v))
            {
                entityReference.EntityKey = null;
            }
            else
            {
                // create a new entity key with the given key component names and key component values
                EntityKey entityKey = new EntityKey(entitySetName, keyComponentNames.Zip(keyValues,
                                                                                         (name, value) => new EntityKeyMember(name, value)));
                entityReference.EntityKey = entityKey;
            }
        }
        /// <summary>
        /// Uses internal API to access metadata for related end target.
        /// </summary>
        /// <param name="relatedEnd">Related end.</param>
        /// <returns>Entity set targeted by the related end.</returns>
        public static EntitySet GetTargetEntitySet(this RelatedEnd relatedEnd)
        {
            EnitityUtility.CheckArgumentNotNull(relatedEnd, "relatedEnd");

            AssociationSet associationSet = (AssociationSet)relatedEnd.RelationshipSet;

            if (null == associationSet)
            {
                //throw new InvalidOperationException(Messages.CannotDetermineMetadataForRelatedEnd);
            }

            return(associationSet.AssociationSetEnds[relatedEnd.TargetRoleName].EntitySet);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Zips together two sequences (aligns values in the two sequences and returns them pair-wise).
        /// </summary>
        /// <typeparam name="TLeft">Element type for the left sequence.</typeparam>
        /// <typeparam name="TRight">Element type for the right sequence.</typeparam>
        /// <typeparam name="TResult">Element type for the result sequence.</typeparam>
        /// <param name="left">Left sequence.</param>
        /// <param name="right">Right sequence.</param>
        /// <param name="resultSelector">Result selector that takes a (left, right) pair.</param>
        /// <returns>Zipped results.</returns>
        public static IEnumerable <TResult> Zip <TLeft, TRight, TResult>(this IEnumerable <TLeft> left, IEnumerable <TRight> right, Func <TLeft, TRight, TResult> resultSelector)
        {
            EnitityUtility.CheckArgumentNotNull(resultSelector, "resultSelector");

            if (null == left || null == right)
            {
                return(Enumerable.Empty <TResult>());
            }
            else
            {
                return(ZipIterator(left, right, resultSelector));
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Construct attribute.
        /// </summary>
        /// <param name="optimizerType">A type implementing the IMaterializerMethodOptimizer interface
        /// that can be used to optimize MethodCallExpressions referencing the attributed method. The
        /// type must have a public default constructor.</param>
        public MaterializerOptimizedMethodAttribute(Type optimizerType)
        {
            EnitityUtility.CheckArgumentNotNull(optimizerType, "optimizerType");

            ConstructorInfo defaultConstructor = optimizerType.GetConstructor(Type.EmptyTypes);

            if (!typeof(IMaterializerMethodOptimizer).IsAssignableFrom(optimizerType) ||
                null == defaultConstructor)
            {
                //throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Messages.InvalidOptimizerType, typeof(IMaterializerMethodOptimizer)), "optimizerType");
            }

            this.optimizer = (IMaterializerMethodOptimizer)defaultConstructor.Invoke(null);
        }
Ejemplo n.º 13
0
        /// <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);
            }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        /// <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;
        }
Ejemplo n.º 17
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>
        ///// 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);
        }
        /// <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);
        }
Ejemplo n.º 21
0
 private static string QuoteIdentifier(string identifier)
 {
     EnitityUtility.CheckArgumentNotNullOrEmpty(identifier, "identifier");
     return("[" + identifier.Replace("]", "]]") + "]");
 }
        /// <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));
        }
        /// <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()));
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
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);
        }