コード例 #1
0
        protected override string GetDbProviderManifestToken(DbConnection connection)
        {
            EntityUtil.CheckArgumentNull(connection, "connection");

            SqlConnection sqlConnection = SqlProviderUtilities.GetRequiredSqlConnection(connection);

            if (string.IsNullOrEmpty(sqlConnection.ConnectionString))
            {
                throw EntityUtil.Argument(Strings.UnableToDetermineStoreVersion);
            }

            string providerManifestToken = null;

            // Try to get the provider manifest token from the database connection
            // That failing, try using connection to master database (in case the database doesn't exist yet)
            try
            {
                UsingConnection(sqlConnection, conn =>
                {
                    providerManifestToken = SqlVersionUtils.GetVersionHint(SqlVersionUtils.GetSqlVersion(conn));
                });
            }
            catch
            {
                UsingMasterConnection(sqlConnection, conn =>
                {
                    providerManifestToken = SqlVersionUtils.GetVersionHint(SqlVersionUtils.GetSqlVersion(conn));
                });
            }
            return(providerManifestToken);
        }
コード例 #2
0
        /// <summary>
        /// A helper method returning the underlying CLR type for the specified OSpace enum or structural type argument.
        /// If the DataSpace of the parameter is not OSpace, the method returns false and sets
        /// the out parameter to null.
        /// </summary>
        /// <param name="objectSpaceType">The OSpace enum type to look up</param>
        /// <param name="clrType">The CLR enum type of the OSpace argument</param>
        /// <returns>true on success, false on failure</returns>
        private static bool TryGetClrType(EdmType objectSpaceType, out Type clrType)
        {
            Debug.Assert(objectSpaceType == null || objectSpaceType is StructuralType || objectSpaceType is EnumType,
                         "Only enum or structural type expected");

            EntityUtil.CheckArgumentNull(objectSpaceType, "objectSpaceType");

            if (objectSpaceType.DataSpace != DataSpace.OSpace)
            {
                throw EntityUtil.Argument(Strings.ArgumentMustBeOSpaceType, "objectSpaceType");
            }

            clrType = null;

            if (Helper.IsEntityType(objectSpaceType) || Helper.IsComplexType(objectSpaceType) || Helper.IsEnumType(objectSpaceType))
            {
                Debug.Assert(objectSpaceType is ClrEntityType || objectSpaceType is ClrComplexType || objectSpaceType is ClrEnumType,
                             "Unexpected OSpace object type.");

                clrType = objectSpaceType.ClrType;

                Debug.Assert(clrType != null, "ClrType property of ClrEntityType/ClrComplexType/ClrEnumType objects must not be null");
            }

            return(clrType != null);
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata">The metadata workspace against which the command tree should operate.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            EntityUtil.CheckArgumentNull(metadata, "metadata");

            // Ensure that the data space value is valid
            if (!DbCommandTree.IsValidDataSpace(dataSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_CommandTree_InvalidDataSpace, "dataSpace");
            }

            //
            // Create the tree's metadata workspace and initalize commonly used types.
            //
            MetadataWorkspace effectiveMetadata = new MetadataWorkspace();

            //While EdmItemCollection and StorageitemCollections are required
            //ObjectItemCollection may or may not be registered on the workspace yet.
            //So register the ObjectItemCollection if it exists.
            ItemCollection objectItemCollection;

            if (metadata.TryGetItemCollection(DataSpace.OSpace, out objectItemCollection))
            {
                effectiveMetadata.RegisterItemCollection(objectItemCollection);
            }
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.SSpace));

            this._metadata  = effectiveMetadata;
            this._dataSpace = dataSpace;
        }
コード例 #4
0
        /// <summary>
        /// Creates metadata for a new row type with column names and types based on the key members of the specified Entity type
        /// </summary>
        /// <param name="entityType">The Entity type that provides the Key members on which the column names and types of the new row type will be based</param>
        /// <returns>A new RowType info with column names and types corresponding to the Key members of the specified Entity type</returns>
        internal static RowType CreateKeyRowType(EntityTypeBase entityType)
        {
            IEnumerable <EdmMember> entityKeys = entityType.KeyMembers;

            if (null == entityKeys)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Metadata_EntityTypeNullKeyMembersInvalid, "entityType");
            }

            List <KeyValuePair <string, TypeUsage> > resultCols = new List <KeyValuePair <string, TypeUsage> >();

            //int idx = 0;
            foreach (EdmProperty keyProperty in entityKeys)
            {
                //this.CheckMember(keyProperty, "property", CommandTreeUtils.FormatIndex("entityType.KeyMembers", idx++));
                resultCols.Add(new KeyValuePair <string, TypeUsage>(keyProperty.Name, Helper.GetModelTypeUsage(keyProperty)));
            }

            if (resultCols.Count < 1)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Metadata_EntityTypeEmptyKeyMembersInvalid, "entityType");
            }

            return(TypeHelpers.CreateRowType(resultCols));
        }
コード例 #5
0
        // SetOp helper - note that this doesn't merge Spans, since Except uses the original query's Span
        // while Intersect/Union/UnionAll use the merged Span.
        private static ObjectQueryState BuildSetOp(ObjectQueryState leftQuery, ObjectQueryState rightQuery, Span newSpan, string setOp)
        {
            // Assert that the arguments aren't null (should have been verified by ObjectQuery)
            Debug.Assert(leftQuery != null, "Left query is null?");
            Debug.Assert(rightQuery != null, "Right query is null?");
            Debug.Assert(leftQuery.ElementType.Equals(rightQuery.ElementType), "Incompatible element types in arguments to Except<T>/Intersect<T>/Union<T>/UnionAll<T>?");

            // Retrieve the left and right arguments to the set operation -
            // this will throw if either input query is not an Entity-SQL query.
            string left  = GetCommandText(leftQuery);
            string right = GetCommandText(rightQuery);

            // ObjectQuery arguments must be associated with the same ObjectContext instance as the implemented query
            if (!object.ReferenceEquals(leftQuery.ObjectContext, rightQuery.ObjectContext))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidQueryArgument, "query");
            }

            // Create a string builder only large enough to contain the new query text
            int           queryLength = _setOpProlog.Length + left.Length + setOp.Length + right.Length + _setOpEpilog.Length;
            StringBuilder builder     = new StringBuilder(queryLength);

            // Build the new query
            builder.Append(_setOpProlog);
            builder.Append(left);
            builder.Append(setOp);
            builder.Append(right);
            builder.Append(_setOpEpilog);

            // Create a new query implementation and apply the state of this implementation to it.
            // The Span of the query argument will be merged into the new query's Span by the caller, iff the Set Op is NOT Except.
            // See the Except, Intersect, Union and UnionAll methods in this class for examples.
            return(NewBuilderQuery(leftQuery, leftQuery.ElementType, builder, newSpan, MergeParameters(leftQuery.Parameters, rightQuery.Parameters)));
        }
コード例 #6
0
ファイル: ExpressionCopier.cs プロジェクト: dox0/DotNet471RS3
        protected override EdmType VisitType(EdmType type)
        {
            EdmType retType = type;

            if (BuiltInTypeKind.RefType == type.BuiltInTypeKind)
            {
                RefType    refType          = (RefType)type;
                EntityType mappedEntityType = (EntityType)this.VisitType(refType.ElementType);
                if (!object.ReferenceEquals(refType.ElementType, mappedEntityType))
                {
                    retType = new RefType(mappedEntityType);
                }
            }
            else if (BuiltInTypeKind.CollectionType == type.BuiltInTypeKind)
            {
                CollectionType collectionType    = (CollectionType)type;
                TypeUsage      mappedElementType = this.VisitTypeUsage(collectionType.TypeUsage);
                if (!object.ReferenceEquals(collectionType.TypeUsage, mappedElementType))
                {
                    retType = new CollectionType(mappedElementType);
                }
            }
            else if (BuiltInTypeKind.RowType == type.BuiltInTypeKind)
            {
                RowType rowType = (RowType)type;
                List <KeyValuePair <string, TypeUsage> > mappedPropInfo = null;
                for (int idx = 0; idx < rowType.Properties.Count; idx++)
                {
                    EdmProperty originalProp   = rowType.Properties[idx];
                    TypeUsage   mappedPropType = this.VisitTypeUsage(originalProp.TypeUsage);
                    if (!object.ReferenceEquals(originalProp.TypeUsage, mappedPropType))
                    {
                        if (mappedPropInfo == null)
                        {
                            mappedPropInfo = new List <KeyValuePair <string, TypeUsage> >(
                                rowType.Properties.Select(
                                    prop => new KeyValuePair <string, TypeUsage>(prop.Name, prop.TypeUsage)
                                    ));
                        }
                        mappedPropInfo[idx] = new KeyValuePair <string, TypeUsage>(originalProp.Name, mappedPropType);
                    }
                }
                if (mappedPropInfo != null)
                {
                    IEnumerable <EdmProperty> mappedProps = mappedPropInfo.Select(propInfo => new EdmProperty(propInfo.Key, propInfo.Value));
                    retType = new RowType(mappedProps, rowType.InitializerMetadata);
                }
            }
            else
            {
                if (!_metadata.TryGetType(type.Name, type.NamespaceName, type.DataSpace, out retType) ||
                    null == retType)
                {
                    throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Copier_TypeNotFound(TypeHelpers.GetFullName(type)));
                }
            }

            return(retType);
        }
コード例 #7
0
        protected override DbProviderManifest GetDbProviderManifest(string versionHint)
        {
            if (string.IsNullOrEmpty(versionHint))
            {
                throw EntityUtil.Argument(Strings.UnableToDetermineStoreVersion);
            }

            return(new SqlProviderManifest(versionHint));
        }
コード例 #8
0
ファイル: EntityParameter.cs プロジェクト: dox0/DotNet471RS3
 /// <summary>
 /// Helper method to validate the parameter name; Ideally we'd only call this once, but
 /// we have to put an argumentName on the Argument exception, and the property setter would
 /// need "value" which confuses folks when they call the constructor that takes the value
 /// of the parameter.  c'est la vie.
 /// </summary>
 /// <param name="parameterName"></param>
 /// <param name="argumentName"></param>
 private void SetParameterNameWithValidation(string parameterName, string argumentName)
 {
     if (!string.IsNullOrEmpty(parameterName) && !DbCommandTree.IsValidParameterName(parameterName))
     {
         throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_InvalidParameterName(parameterName), argumentName);
     }
     PropertyChanging();
     this._parameterName = parameterName;
 }
コード例 #9
0
        /// <summary>
        /// Requires that the given connection is of type  T.
        /// Returns the connection or throws.
        /// </summary>
        internal static SqlConnection GetRequiredSqlConnection(DbConnection connection)
        {
            var result = connection as SqlConnection;

            if (null == result)
            {
                throw EntityUtil.Argument(Strings.Mapping_Provider_WrongConnectionType(typeof(SqlConnection)));
            }
            return(result);
        }
コード例 #10
0
        protected override string GetDbProviderManifestToken(DbConnection connection)
        {
            EntityUtil.CheckArgumentNull(connection, "connection");
            if (connection.GetType() != typeof(EntityConnection))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Mapping_Provider_WrongConnectionType(typeof(EntityConnection)));
            }

            return(MetadataItem.EdmProviderManifest.Token);
        }
コード例 #11
0
 // using EntitySetBase versus EntitySet prevents the unnecessary cast of ElementType to EntityType
 private void ValidateEntityType(EntitySetBase entitySet)
 {
     if (!object.ReferenceEquals(RecordType.EdmType, null) &&
         !object.ReferenceEquals(_entityKey, EntityKey.EntityNotValidKey) &&
         !object.ReferenceEquals(_entityKey, EntityKey.NoEntitySetKey) &&
         !object.ReferenceEquals(RecordType.EdmType, entitySet.ElementType) &&
         !entitySet.ElementType.IsBaseTypeOf(RecordType.EdmType))
     {
         throw EntityUtil.Argument(System.Data.Entity.Strings.EntityTypesDoNotAgree);
     }
 }
        /// <summary>
        ///   This query-builder method creates a new query whose results are the
        ///   first 'count' results of this query.
        /// </summary>
        /// <param name="count">
        ///   Specifies the number of results to return. This must be either a constant or
        ///   a parameter reference.
        /// </param>
        /// <param name="parameters">
        ///   An optional set of query parameters that should be in scope when parsing.
        /// </param>
        /// <returns>
        ///   a new ObjectQuery instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If the top count command text is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   If the top count command text is empty.
        /// </exception>
        public ObjectQuery <T> Top(string count, params ObjectParameter[] parameters)
        {
            EntityUtil.CheckArgumentNull(count, "count");

            if (StringUtil.IsNullOrEmptyOrWhiteSpace(count))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidTopCount, "count");
            }

            return(new ObjectQuery <T>(EntitySqlQueryBuilder.Top(this.QueryState, this.Name, count, parameters)));
        }
        /// <summary>
        ///   This query-builder method creates a new query whose results are the
        ///   results of this query filtered by some criteria.
        /// </summary>
        /// <param name="predicate">
        ///   The filter predicate.
        /// </param>
        /// <param name="parameters">
        ///   An optional set of query parameters that should be in scope when parsing.
        /// </param>
        /// <returns>
        ///   a new ObjectQuery instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If either argument is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   If the filter predicate command text is empty.
        /// </exception>
        public ObjectQuery <T> Where(string predicate, params ObjectParameter[] parameters)
        {
            EntityUtil.CheckArgumentNull(predicate, "predicate");
            EntityUtil.CheckArgumentNull(parameters, "parameters");

            if (StringUtil.IsNullOrEmptyOrWhiteSpace(predicate))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidFilterPredicate, "predicate");
            }

            return(new ObjectQuery <T>(EntitySqlQueryBuilder.Where(this.QueryState, this.Name, predicate, parameters)));
        }
        /// <summary>
        ///   This query-builder method creates a new query whose results are the
        ///   results of this query, ordered by some criteria. Note that any relational
        ///   operations performed after an OrderBy have the potential to "undo" the
        ///   ordering, so OrderBy should be considered a terminal query-building
        ///   operation.
        /// </summary>
        /// <param name="keys">
        ///   The sort keys.
        /// </param>
        /// <param name="parameters">
        ///   An optional set of query parameters that should be in scope when parsing.
        /// </param>
        /// <returns>
        ///   a new ObjectQuery instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If either argument is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   If the sort key command text is empty.
        /// </exception>
        public ObjectQuery <T> OrderBy(string keys, params ObjectParameter[] parameters)
        {
            EntityUtil.CheckArgumentNull(keys, "keys");
            EntityUtil.CheckArgumentNull(parameters, "parameters");

            if (StringUtil.IsNullOrEmptyOrWhiteSpace(keys))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidSortKeyList, "keys");
            }

            return(new ObjectQuery <T>(EntitySqlQueryBuilder.OrderBy(this.QueryState, this.Name, keys, parameters)));
        }
        /// <summary>
        ///   This query-builder method creates a new query whose results are data
        ///   records containing selected fields of the results of this query.
        /// </summary>
        /// <param name="projection">
        ///   The projection list.
        /// </param>
        /// <param name="parameters">
        ///   An optional set of query parameters that should be in scope when parsing.
        /// </param>
        /// <returns>
        ///   a new ObjectQuery instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If either argument is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   If the projection list command text is empty.
        /// </exception>
        public ObjectQuery <DbDataRecord> Select(string projection, params ObjectParameter[] parameters)
        {
            EntityUtil.CheckArgumentNull(projection, "projection");
            EntityUtil.CheckArgumentNull(parameters, "parameters");

            if (StringUtil.IsNullOrEmptyOrWhiteSpace(projection))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidProjectionList, "projection");
            }

            return(new ObjectQuery <DbDataRecord>(EntitySqlQueryBuilder.Select(this.QueryState, this.Name, projection, parameters)));
        }
コード例 #16
0
        /// <summary>
        /// Creates a new query instance using the given LINQ expresion.
        /// The current query is used to produce the context for the new query, but none of its logic
        /// is used.
        /// </summary>
        /// <typeparam name="S">Element type for query result.</typeparam>
        /// <param name="expression">LINQ expression forming the query.</param>
        /// <returns>ObjectQuery implementing the expression logic.</returns>
        IQueryable <S> IQueryProvider.CreateQuery <S>(Expression expression)
        {
            EntityUtil.CheckArgumentNull(expression, "expression");
            if (!typeof(IQueryable <S>).IsAssignableFrom(expression.Type))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ELinq_ExpressionMustBeIQueryable, "expression");
            }

            ObjectQuery <S> query = CreateQuery <S>(expression);

            return(query);
        }
コード例 #17
0
        private static SqlVersion GetSqlVersion(StoreItemCollection storeItemCollection)
        {
            SqlProviderManifest sqlManifest = (storeItemCollection.StoreProviderManifest as SqlProviderManifest);

            if (sqlManifest == null)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Mapping_Provider_WrongManifestType(typeof(SqlProviderManifest)));
            }
            SqlVersion sqlVersion = sqlManifest.SqlVersion;

            return(sqlVersion);
        }
コード例 #18
0
ファイル: ValueExpressions.cs プロジェクト: dox0/DotNet471RS3
        internal DbRelatedEntityRef(RelationshipEndMember sourceEnd, RelationshipEndMember targetEnd, DbExpression targetEntityRef)
        {
            // Validate that the specified relationship ends are:
            // 1. Non-null
            // 2. From the same metadata workspace as that used by the command tree
            EntityUtil.CheckArgumentNull(sourceEnd, "sourceEnd");
            EntityUtil.CheckArgumentNull(targetEnd, "targetEnd");

            // Validate that the specified target entity ref is:
            // 1. Non-null
            EntityUtil.CheckArgumentNull(targetEntityRef, "targetEntityRef");

            // Validate that the specified source and target ends are:
            // 1. Declared by the same relationship type
            if (!object.ReferenceEquals(sourceEnd.DeclaringType, targetEnd.DeclaringType))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndFromDifferentRelationship, "targetEnd");
            }
            // 2. Not the same end
            if (object.ReferenceEquals(sourceEnd, targetEnd))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndSameAsSourceEnd, "targetEnd");
            }

            // Validate that the specified target end has multiplicity of at most one
            if (targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.One &&
                targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndMustBeAtMostOne, "targetEnd");
            }

            // Validate that the specified target entity ref actually has a ref result type
            if (!TypeSemantics.IsReferenceType(targetEntityRef.ResultType))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotRef, "targetEntityRef");
            }

            // Validate that the specified target entity is of a type that can be reached by navigating to the specified relationship end
            EntityTypeBase endType    = TypeHelpers.GetEdmType <RefType>(targetEnd.TypeUsage).ElementType;
            EntityTypeBase targetType = TypeHelpers.GetEdmType <RefType>(targetEntityRef.ResultType).ElementType;

            //
            if (!endType.EdmEquals(targetType) && !TypeSemantics.IsSubTypeOf(targetType, endType))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotCompatible, "targetEntityRef");
            }

            // Validation succeeded, initialize state
            _targetEntityRef = targetEntityRef;
            _targetEnd       = targetEnd;
            _sourceEnd       = sourceEnd;
        }
コード例 #19
0
        /// <summary>
        /// Initializes a new query EntitySqlQueryState instance.
        /// </summary>
        /// <param name="context">
        ///     The ObjectContext containing the metadata workspace the query was
        ///     built against, the connection on which to execute the query, and the
        ///     cache to store the results in. Must not be null.
        /// </param>
        /// <param name="commandText">
        ///     The Entity-SQL text of the query
        /// </param>
        /// <param name="expression">
        ///     Optional <see cref="DbExpression"/> that defines the query. Must be semantically equal to the <paramref name="commandText"/>.
        /// </param>
        /// <param name="mergeOption">
        ///     The merge option to use when retrieving results if an explicit merge option is not specified
        /// </param>
        internal EntitySqlQueryState(Type elementType, string commandText, DbExpression expression, bool allowsLimit, ObjectContext context, ObjectParameterCollection parameters, Span span)
            : base(elementType, context, parameters, span)
        {
            EntityUtil.CheckArgumentNull(commandText, "commandText");
            if (string.IsNullOrEmpty(commandText))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_InvalidEmptyQuery, "commandText");
            }

            _queryText       = commandText;
            _queryExpression = expression;
            _allowsLimit     = allowsLimit;
        }
コード例 #20
0
ファイル: ValueExpressions.cs プロジェクト: dox0/DotNet471RS3
        internal MethodExpression(CommandTree cmdTree, MethodMetadata methodInfo, IList <Expression> args, Expression instance)
            : base(cmdTree, ExpressionKind.Method)
        {
            //
            // Ensure that the property metadata is non-null and from the same metadata workspace and dataspace as the command tree.
            //
            CommandTreeTypeHelper.CheckMember(methodInfo, "method", "methodInfo");

            //
            // Methods that return void are not allowed
            //
            if (cmdTree.TypeHelper.IsNullOrNullType(methodInfo.Type))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_VoidResultInvalid, "methodInfo");
            }

            if (null == args)
            {
                throw EntityUtil.ArgumentNull("args");
            }

            this.m_inst = new ExpressionLink("Instance", cmdTree);

            //
            // Validate the instance
            //
            if (methodInfo.IsStatic)
            {
                if (instance != null)
                {
                    throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_InstanceInvalidForStatic, "instance");
                }
            }
            else
            {
                if (null == instance)
                {
                    throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_InstanceRequiredForInstance, "instance");
                }

                this.m_inst.SetExpectedType(methodInfo.DefiningType);
                this.m_inst.InitializeValue(instance);
            }

            //
            // Validate the arguments
            //
            m_args          = new ExpressionList("Arguments", cmdTree, methodInfo.Parameters, args);
            m_methodInfo    = methodInfo;
            this.ResultType = methodInfo.Type;
        }
コード例 #21
0
        /// <summary>
        /// A helper method returning the underlying CLR type for the specified OSpace Enum or Structural type argument.
        /// If the DataSpace of the parameter is not OSpace, an ArgumentException is thrown.
        /// </summary>
        /// <param name="objectSpaceType">The OSpace type to look up</param>
        /// <returns>The CLR type of the OSpace argument</returns>
        private static Type GetClrType(EdmType objectSpaceType)
        {
            Debug.Assert(objectSpaceType == null || objectSpaceType is StructuralType || objectSpaceType is EnumType,
                         "Only enum or structural type expected");

            Type clrType;

            if (!ObjectItemCollection.TryGetClrType(objectSpaceType, out clrType))
            {
                throw EntityUtil.Argument(Strings.FailedToFindClrTypeMapping(objectSpaceType.Identity));
            }

            return(clrType);
        }
        /// <summary>
        ///   This query-builder method creates a new query whose results are a sequence
        ///   of values projected from the results of this query.
        /// </summary>
        /// <param name="projection">
        ///   The projection list.
        /// </param>
        /// <param name="parameters">
        ///   An optional set of query parameters that should be in scope when parsing.
        /// </param>
        /// <returns>
        ///   a new ObjectQuery instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If either argument is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   If the projection list command text is empty.
        /// </exception>
        public ObjectQuery <TResultType> SelectValue <TResultType> (string projection, params ObjectParameter[] parameters)
        {
            EntityUtil.CheckArgumentNull(projection, "projection");
            EntityUtil.CheckArgumentNull(parameters, "parameters");

            if (StringUtil.IsNullOrEmptyOrWhiteSpace(projection))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidProjectionList, "projection");
            }

            // SQLPUDT 484974: Make sure TResultType is loaded.
            this.QueryState.ObjectContext.MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(TResultType), System.Reflection.Assembly.GetCallingAssembly());

            return(new ObjectQuery <TResultType>(EntitySqlQueryBuilder.SelectValue(this.QueryState, this.Name, projection, parameters, typeof(TResultType))));
        }
コード例 #23
0
        /// <summary>
        /// Creates a new query instance using the given LINQ expresion.
        /// The current query is used to produce the context for the new query, but none of its logic
        /// is used.
        /// </summary>
        /// <param name="expression">Expression forming the query.</param>
        /// <returns>ObjectQuery instance implementing the given expression.</returns>
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            EntityUtil.CheckArgumentNull(expression, "expression");
            if (!typeof(IQueryable).IsAssignableFrom(expression.Type))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ELinq_ExpressionMustBeIQueryable, "expression");
            }

            // Determine the type of the query instance by binding generic parameter in Query<>.Queryable
            // (based on element type of expression)
            Type        elementType = TypeSystem.GetElementType(expression.Type);
            ObjectQuery query       = CreateQuery(expression, elementType);

            return(query);
        }
コード例 #24
0
        internal static DbProviderFactory GetProviderFactory(string providerInvariantName)
        {
            EntityUtil.CheckArgumentNull(providerInvariantName, "providerInvariantName");
            DbProviderFactory factory;

            try
            {
                factory = DbProviderFactories.GetFactory(providerInvariantName);
            }
            catch (ArgumentException e)
            {
                throw EntityUtil.Argument(Strings.EntityClient_InvalidStoreProvider, e);
            }
            return(factory);
        }
コード例 #25
0
        void ValidateVersionHint(string versionHint)
        {
            if (string.IsNullOrEmpty(versionHint))
            {
                throw EntityUtil.Argument(Strings.UnableToDetermineStoreVersion);
            }

            // GetSqlVersion will throw ArgumentException if manifestToken is null, empty, or not recognized.
            SqlVersion tokenVersion = SqlVersionUtils.GetSqlVersion(versionHint);

            // SQL spatial support is only available for SQL Server 2008 and later
            if (tokenVersion < SqlVersion.Sql10)
            {
                throw EntityUtil.ProviderIncompatible(Strings.SqlProvider_Sql2008RequiredForSpatial);
            }
        }
コード例 #26
0
        internal static string GetVersionHint(SqlVersion version)
        {
            switch (version)
            {
            case SqlVersion.Sql8:
                return(SqlProviderManifest.TokenSql8);

            case SqlVersion.Sql9:
                return(SqlProviderManifest.TokenSql9);

            case SqlVersion.Sql10:
                return(SqlProviderManifest.TokenSql10);

            default:
                throw EntityUtil.Argument(Strings.UnableToDetermineStoreVersion);
            }
        }
コード例 #27
0
        // -------------------
        // Public Constructors
        // -------------------

        #region ObjectParameter (string, Type)

        /// <summary>
        ///   This constructor creates an unbound (i.e., value-less) parameter from the
        ///   specified name and type. The value can be set at any time through the
        ///   public 'Value' property.
        /// </summary>
        /// <param name="name">
        ///   The parameter name.
        /// </param>
        /// <param name="type">
        ///   The CLR type of the parameter.
        /// </param>
        /// <returns>
        ///   A new unbound ObjectParameter instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   If the value of either argument is null.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   If the value of the name argument is invalid. Parameter names must start
        ///   with a letter and may only contain letters (A-Z, a-z), numbers (0-9) and
        ///   underscores (_).
        /// </exception>
        public ObjectParameter(string name, Type type)
        {
            EntityUtil.CheckArgumentNull(name, "name");
            EntityUtil.CheckArgumentNull(type, "type");

            if (!ObjectParameter.ValidateParameterName(name))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectParameter_InvalidParameterName(name), "name");
            }

            this._name = name;
            this._type = type;

            // If the parameter type is Nullable<>, we need to extract out the underlying
            // Nullable<> type argument.
            this._mappableType = System.Data.Objects.ELinq.TypeSystem.GetNonNullableType(this._type);
        }
コード例 #28
0
        /// <summary>
        /// Main entry point for parsing cql.
        /// </summary>
        /// <param name="query">query text</param>
        /// <exception cref="System.Data.EntityException">Thrown when Syntatic rules are violated and the query cannot be accepted</exception>
        /// <returns>Abstract Syntax Tree</returns>
        internal Node Parse(string query)
        {
            // The common practice is to make the null check at the public surface,
            // however this method is a convergence zone from multiple public entry points and it makes sense to
            // check for null once, here.
            EntityUtil.CheckArgumentNull(query, "query");
            if (String.IsNullOrEmpty(query) || query.Trim().Length == 0)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.InvalidEmptyQueryTextArgument);
            }

            _query                  = query;
            _parsedTree             = null;
            _methodExprCounter      = 0;
            _methodExprCounterStack = new Stack <uint>();
            internalParseEntryPoint();
            return(_parsedTree);
        }
コード例 #29
0
ファイル: ExpressionCopier.cs プロジェクト: dox0/DotNet471RS3
        protected override EdmFunction VisitFunction(EdmFunction function)
        {
            List <TypeUsage> paramTypes = new List <TypeUsage>(function.Parameters.Count);

            foreach (FunctionParameter funcParam in function.Parameters)
            {
                TypeUsage mappedParamType = this.VisitTypeUsage(funcParam.TypeUsage);
                paramTypes.Add(mappedParamType);
            }

            if (DataSpace.SSpace == function.DataSpace)
            {
                EdmFunction foundFunc = null;
                if (_metadata.TryGetFunction(function.Name,
                                             function.NamespaceName,
                                             paramTypes.ToArray(),
                                             false /* ignoreCase */,
                                             function.DataSpace,
                                             out foundFunc) &&
                    foundFunc != null)
                {
                    return(foundFunc);
                }
            }
            else
            {
                // Find the function or function import.
                IList <EdmFunction> candidateFunctions;
                if (_perspective.TryGetFunctionByName(function.NamespaceName, function.Name, /*ignoreCase:*/ false, out candidateFunctions))
                {
                    Debug.Assert(null != candidateFunctions && candidateFunctions.Count > 0, "Perspective.TryGetFunctionByName returned true with null/empty function result list");

                    bool        isAmbiguous;
                    EdmFunction retFunc = FunctionOverloadResolver.ResolveFunctionOverloads(candidateFunctions, paramTypes, /*isGroupAggregateFunction:*/ false, out isAmbiguous);
                    if (!isAmbiguous &&
                        retFunc != null)
                    {
                        return(retFunc);
                    }
                }
            }

            throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Copier_FunctionNotFound(TypeHelpers.GetFullName(function)));
        }
コード例 #30
0
ファイル: ExpressionCopier.cs プロジェクト: dox0/DotNet471RS3
        protected override EntitySetBase VisitEntitySet(EntitySetBase entitySet)
        {
            EntityContainer container;

            if (_metadata.TryGetEntityContainer(entitySet.EntityContainer.Name, entitySet.EntityContainer.DataSpace, out container))
            {
                EntitySetBase extent = null;
                if (container.BaseEntitySets.TryGetValue(entitySet.Name, false, out extent) &&
                    extent != null &&
                    entitySet.BuiltInTypeKind == extent.BuiltInTypeKind) // EntitySet -> EntitySet, AssociationSet -> AssociationSet, etc
                {
                    return(extent);
                }

                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Copier_EntitySetNotFound(entitySet.EntityContainer.Name, entitySet.Name));
            }

            throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Copier_EntityContainerNotFound(entitySet.EntityContainer.Name));
        }