public IQueryable CreateQuery(Expression expression)
        {
            Type elementType = TypeSystem.GetElementType(expression.Type);

            try
            {
                return((IQueryable)Activator.CreateInstance(
                           typeof(VulkanComputeQuery <>).MakeGenericType(elementType), this, expression));
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }
 /// <summary>
 /// Cast changes the type of the ResourceExpression
 /// </summary>
 /// <param name="type">new type</param>
 /// <returns>new NavigationPropertySingletonExpression</returns>
 internal override ResourceExpression CreateCloneWithNewType(Type type)
 {
     return(new NavigationPropertySingletonExpression(
                type,
                this.source,
                this.MemberExpression,
                TypeSystem.GetElementType(type),
                this.ExpandPaths.ToList(),
                this.CountOption,
                this.CustomQueryOptions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                this.Projection,
                this.ResourceTypeAs,
                this.UriVersion));
 }
 internal Expression GetDataMemberQuery(MetaDataMember member, Expression[] keyValues)
 {
     if (member == null)
     {
         throw Error.ArgumentNull("member");
     }
     if (keyValues == null)
     {
         throw Error.ArgumentNull("keyValues");
     }
     if (member.IsAssociation)
     {
         MetaAssociation association = member.Association;
         Type            rootType    = association.ThisMember.DeclaringType.InheritanceRoot.Type;
         Expression      thisSource  = Expression.Constant(_context.GetTable(rootType));
         if (rootType != association.ThisMember.DeclaringType.Type)
         {
             thisSource = Expression.Call(typeof(Enumerable), "Cast", new Type[] { association.ThisMember.DeclaringType.Type }, thisSource);
         }
         Expression thisInstance = Expression.Call(typeof(Enumerable), "FirstOrDefault", new Type[] { association.ThisMember.DeclaringType.Type },
                                                   Translator.WhereClauseFromSourceAndKeys(thisSource, association.ThisKey.ToArray(), keyValues)
                                                   );
         Expression otherSource = Expression.Constant(_context.GetTable(association.OtherType.InheritanceRoot.Type));
         if (association.OtherType.Type != association.OtherType.InheritanceRoot.Type)
         {
             otherSource = Expression.Call(typeof(Enumerable), "Cast", new Type[] { association.OtherType.Type }, otherSource);
         }
         Expression expr = Translator.TranslateAssociation(
             this._context, association, otherSource, keyValues, thisInstance
             );
         return(expr);
     }
     else
     {
         Expression          query       = this.GetObjectQuery(member.DeclaringType, keyValues);
         Type                elementType = TypeSystem.GetElementType(query.Type);
         ParameterExpression p           = Expression.Parameter(elementType, "p");
         Expression          e           = p;
         if (elementType != member.DeclaringType.Type)
         {
             e = Expression.Convert(e, member.DeclaringType.Type);
         }
         Expression mem = (member.Member is PropertyInfo)
                                 ? Expression.Property(e, (PropertyInfo)member.Member)
                                 : Expression.Field(e, (FieldInfo)member.Member);
         LambdaExpression selector = Expression.Lambda(mem, p);
         return(Expression.Call(typeof(Queryable), "Select", new Type[] { elementType, selector.Body.Type }, query, selector));
     }
 }
Exemple #4
0
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            if (expression == null)
            {
                throw Error.ArgumentNull("expression");
            }
            Type elementType = TypeSystem.GetElementType(expression.Type);
            Type type2       = typeof(IQueryable <>).MakeGenericType(new[] { elementType });

            if (!type2.IsAssignableFrom(expression.Type))
            {
                throw Error.ExpectedQueryableArgument("expression", type2);
            }
            return((IQueryable)Activator.CreateInstance(typeof(DataQuery <>).MakeGenericType(new[] { elementType }), new object[] { context, expression }));
        }
Exemple #5
0
        public IDeferredSourceFactory GetDeferredSourceFactory(MetaDataMember member)
        {
            IDeferredSourceFactory factory;

            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }
            if (!factoryMap.TryGetValue(member, out factory))
            {
                Type type = (member.IsAssociation && member.Association.IsMany) ? TypeSystem.GetElementType(member.Type) : member.Type;
                factory = (IDeferredSourceFactory)Activator.CreateInstance(typeof(DeferredSourceFactory <>).MakeGenericType(new[] { type }), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { member, this }, null);
                factoryMap.Add(member, factory);
            }
            return(factory);
        }
Exemple #6
0
        /// <summary>
        /// Applies the sequence projection.
        /// </summary>
        /// <param name="sourceSequenceExpression">
        /// The source sequence expression.
        /// </param>
        /// <param name="projectionType">
        /// Type of the projection.
        /// </param>
        /// <param name="projectionConfig">
        /// The projection config.
        /// </param>
        /// <returns>
        /// New sequence expression with applied projection.
        /// </returns>
        private Expression ApplySequenceProjection(Expression sourceSequenceExpression, Type projectionType, object projectionConfig)
        {
            var sourceElementType = TypeSystem.GetElementType(sourceSequenceExpression.Type);

            ValidateProjectionType(sourceElementType, projectionType);

            // todo: add cache
            // todo: encapsulate this logic somewhere outside
            var resultSequenceExpression = GetProjectionMembers(projectionType, projectionConfig)
                                           .OrderBy(memberGroup => memberGroup.Key) // note: ordering by enum underlying int values, order is significant
                                           .Aggregate(
                sourceSequenceExpression,
                (previous, memberGroup) => this.MemberTypeHandlers[memberGroup.Key](previous, projectionType, projectionConfig, memberGroup));

            return(resultSequenceExpression);
        }
Exemple #7
0
        /// <summary>
        /// Checks whether the specified expression creates a collection.
        /// </summary>
        /// <param name="e">Expression to check.</param>
        /// <returns>true if given expression is collection producing.</returns>
        internal static bool IsCollectionProducingExpression(Expression e)
        {
            if (TypeSystem.FindIEnumerable(e.Type) != null)
            {
                Type elementType = TypeSystem.GetElementType(e.Type);
                Debug.Assert(elementType != null, "elementType == null");
                Type dscType = WebUtil.GetDataServiceCollectionOfT(elementType);
                if (typeof(List <>).MakeGenericType(elementType).IsAssignableFrom(e.Type) ||
                    (dscType != null && dscType.IsAssignableFrom(e.Type)))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #8
0
        /// <summary>
        /// This method is trying to distinguish between a set of types and a singleton type
        /// It also has the restriction that to be a set of types, it must be assignable from ObjectQuery&lt;T&gt;
        /// Otherwise we won't be able to cast our query to the set requested.
        /// </summary>
        /// <param name="resultType">The type asked for as a result type.</param>
        /// <param name="isSingleton">Is it a set of a type.</param>
        /// <returns>The element type to use</returns>
        private static Type GetElementType(Type resultType, out bool isSingleton)
        {
            Type elementType = TypeSystem.GetElementType(resultType);

            isSingleton = (elementType == resultType ||
                           !resultType.IsAssignableFrom(typeof(ObjectQuery <>).MakeGenericType(elementType)));

            if (isSingleton)
            {
                return(resultType);
            }
            else
            {
                return(elementType);
            }
        }
Exemple #9
0
        /// <summary>
        /// Constructs an <see cref="T:System.Linq.IQueryable"/> object that can evaluate the query represented by a specified expression tree.
        /// </summary>
        /// <param name="expression">
        /// An expression tree that represents a LINQ query.
        /// </param>
        /// <returns>
        /// An <see cref="T:System.Linq.IQueryable"/> that can evaluate the query represented by the specified expression tree.
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public IQueryable CreateQuery(Expression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            Type elementType = TypeSystem.GetElementType(expression.Type);

            if (!typeof(IQueryable <>).MakeGenericType(elementType).IsAssignableFrom(expression.Type))
            {
                throw new ArgumentException("Invalid type expression", "expression");
            }

            return((IQueryable)Activator.CreateInstance(typeof(MemoryQueryable <>).MakeGenericType(elementType), new object[] { this, expression }));
        }
Exemple #10
0
        public DbContext(string connectionString)
        {
            DbQuery = new DbQuery(connectionString);

            var properties = GetType()
                             .GetProperties(/*BindingFlags.Public | BindingFlags.Instance*/)
                             .Where(it => TypeSystem.IsTypeAssignable(it.PropertyType, typeof(DbQueryable <>)));

            foreach (var property in properties)
            {
                Type elementType        = TypeSystem.GetElementType(property.PropertyType);
                var  collectionInstance = Activator
                                          .CreateInstance(typeof(DbQueryable <>).MakeGenericType(elementType), new object[] { DbQuery });
                property.SetValue(this, collectionInstance);
            }
        }
Exemple #11
0
        /// <summary>
        /// Execute a projection on the list
        /// </summary>
        /// <typeparam name="T">Type being processed</typeparam>
        /// <param name="list">List to process</param>
        /// <param name="lambdaExpr">Lambda with projection</param>
        /// <returns>List of projected types</returns>
        internal IEnumerable ProcessSelect <T>(IEnumerable <T> list, LambdaExpression lambdaExpr)
        {
            Type resultType = TypeSystem.GetElementType(lambdaExpr.Body.Type);

            var methodInfo =
                typeof(Enumerable)
                .GetMethods()
                .Where(
                    meth => meth.Name == "Select" &&
                    meth.GetGenericArguments().Count() == 2)
                .FirstOrDefault();

            Type[]     genericArguments  = new Type[] { typeof(T), resultType };
            MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);

            return((IEnumerable)genericMethodInfo.Invoke(null, new object[] { list, lambdaExpr.Compile() }));
        }
Exemple #12
0
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            if (expression == null)
            {
                throw Error.ArgumentNull("expression");
            }
            Type eType = TypeSystem.GetElementType(expression.Type);
            Type qType = typeof(IQueryable <>).MakeGenericType(eType);

            if (!qType.IsAssignableFrom(expression.Type))
            {
                throw Error.ExpectedQueryableArgument("expression", qType);
            }
            Type dqType = typeof(DataQuery <>).MakeGenericType(eType);

            return((IQueryable)Activator.CreateInstance(dqType, new object[] { this.context, expression }));
        }
Exemple #13
0
 public object GetCachedObject(Expression query)
 {
     if (query != null)
     {
         string str;
         var    expression = query as MethodCallExpression;
         if ((expression == null) || (expression.Arguments.Count != 2))
         {
             return(null);
         }
         if ((expression.Method.DeclaringType != typeof(Queryable)) && (((str = expression.Method.Name) == null) || ((((str != "Where") && (str != "First")) && ((str != "FirstOrDefault") && (str != "Single"))) && (str != "SingleOrDefault"))))
         {
             return(null);
         }
         var expression2 = expression.Arguments[1] as UnaryExpression;
         if ((expression2 == null) || (expression2.NodeType != ExpressionType.Quote))
         {
             return(null);
         }
         var operand = expression2.Operand as LambdaExpression;
         if (operand != null)
         {
             var expression4 = expression.Arguments[0] as ConstantExpression;
             if (expression4 == null)
             {
                 return(null);
             }
             var table = expression4.Value as ITable;
             if (table == null)
             {
                 return(null);
             }
             if (TypeSystem.GetElementType(query.Type) != table.ElementType)
             {
                 return(null);
             }
             MetaTable table2    = Model.GetTable(table.ElementType);
             object[]  keyValues = GetKeyValues(table2.RowType, operand);
             if (keyValues != null)
             {
                 return(GetCachedObject(table2.RowType, keyValues));
             }
         }
     }
     return(null);
 }
        public IQueryable CreateQuery(Expression expression)
        {
            CommonUtility.AssertNotNull("expression", expression);
            Type elementType = TypeSystem.GetElementType(expression.Type);

            Type queryType = typeof(TableQuery <>).MakeGenericType(elementType);

            object[] args = new object[] { expression, this };

            ConstructorInfo ci = queryType.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new Type[] { typeof(Expression), typeof(TableQueryProvider) },
                null);

            return((IQueryable)ConstructorInvoke(ci, args));
        }
Exemple #15
0
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            if (expression == null)
            {
                throw Error.ArgumentNull("expression");
            }
            var elementType = TypeSystem.GetElementType(expression.Type);
            var type        = typeof(IQueryable <>).MakeGenericType(elementType);

            if (!type.IsAssignableFrom(expression.Type))
            {
                throw Error.ExpectedQueryableArgument("expression", type);
            }
            var type2 = typeof(DataQuery <>).MakeGenericType(elementType);

            return((IQueryable)Activator.CreateInstance(type2, context, expression));
        }
Exemple #16
0
        private Property SerializeProperty(Type parentType, Type propType, IList list)
        {
            var isIndexed = IsPropertyIndexed(parentType, propType.Name);

            var values           = new List <Value>();
            var enumerator       = list.GetEnumerator();
            var genericParamType = TypeSystem.GetElementType(propType);

            while (enumerator.MoveNext())
            {
                values.Add(ConvertPropertyToValue(SerializeProperty(genericParamType, enumerator.Current, isIndexed)));
            }

            return(new Property {
                ListValue = values, Indexed = isIndexed
            });
        }
Exemple #17
0
        public IQueryable CreateQuery(System.Linq.Expressions.Expression expression)
        {
            Type elementType = TypeSystem.GetElementType(expression.Type);

            try
            {
#if JAVA
                return((IQueryable)Activator.CreateInstance(typeof(TayzGridQuery <>).MakeGenericType(elementType), new object[] { this, expression }));
#else
                return((IQueryable)Activator.CreateInstance(typeof(NCacheQuery <>).MakeGenericType(elementType), new object[] { this, expression }));
#endif
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }
Exemple #18
0
        public TResult Execute <TResult>(Expression expression)
        {
            var type = typeof(TResult);
            //var mapper = DataEngine.ColumnMapper.TryGetMapper(type);
            //if (mapper != null)
            //{
            //    var sqlExpression = ExecuteImp(expression, typeof(SelectExpression));
            //    var scalar = DataEngine.ExecuteScalar(sqlExpression, type);
            //    return (TResult)scalar;
            //}

            var elementType = TypeSystem.GetElementType(expression.Type);
            var list        = Select(expression);

            if (typeof(TResult) == elementType)
            {
                var enumerator           = list.GetEnumerator();
                var methodCallExpression = expression as MethodCallExpression;
                if (methodCallExpression == null)
                {
                    throw new InvalidOperationException();
                }
                switch (methodCallExpression.Method.Name)
                {
                case "FirstOrDefault":
                    return(First <TResult>(enumerator, true));

                case "First":
                    return(First <TResult>(enumerator, false));

                case "SingleOrDefault":
                    return(Single <TResult>(enumerator, true));

                case "Single":
                    return(Single <TResult>(enumerator, false));

                case "Count":
                    enumerator.MoveNext();
                    return((TResult)enumerator.Current);

                default:
                    throw new NotSupportedException(methodCallExpression.Method.Name);
                }
            }
            return((TResult)list);
        }
        // Methods
        internal AttributedMetaAssociation(AttributedMetaDataMember member, AssociationAttribute attr)
        {
            this.attributeProvider = member.MetaModel.AttributeProvider;

            this.thisMember = member;
            this.isMany     = TypeSystem.IsSequenceType(thisMember.Type);
            Type type = this.isMany ? TypeSystem.GetElementType(thisMember.Type) : thisMember.Type;

            this.otherType            = this.thisMember.DeclaringType.Model.GetMetaType(type);
            this.thisKey              = (attr.ThisKey != null) ? MakeKeys(thisMember.DeclaringType, attr.ThisKey) : thisMember.DeclaringType.IdentityMembers;
            this.otherKey             = (attr.OtherKey != null) ? MakeKeys(otherType, attr.OtherKey) : this.otherType.IdentityMembers;
            this.thisKeyIsPrimaryKey  = AreEqual(this.thisKey, thisMember.DeclaringType.IdentityMembers);
            this.otherKeyIsPrimaryKey = AreEqual(this.otherKey, otherType.IdentityMembers);
            this.isForeignKey         = attr.IsForeignKey;
            this.isUnique             = attr.IsUnique;
            this.deleteRule           = attr.DeleteRule;
            this.deleteOnNull         = attr.DeleteOnNull;
            foreach (MetaDataMember member2 in this.thisKey)
            {
                if (!member2.CanBeNull)
                {
                    this.isNullable = false;
                    break;
                }
            }
            if (this.deleteOnNull && ((!this.isForeignKey || this.isMany) || this.isNullable))
            {
                throw Mapping.Error.InvalidDeleteOnNullSpecification(member);
            }
            if (((this.thisKey.Count != this.otherKey.Count) && (this.thisKey.Count > 0)) && (this.otherKey.Count > 0))
            {
                throw Mapping.Error.MismatchedThisKeyOtherKey(member.Name, member.DeclaringType.Name);
            }
            foreach (MetaDataMember member3 in this.otherType.PersistentDataMembers)
            {
                /* var customAttribute = (AssociationAttribute)Attribute.GetCustomAttribute(member3.Member, typeof(AssociationAttribute)); */
                var customAttribute = this.attributeProvider.GetAssociationAttribute(member3.Member);

                if (((customAttribute != null) && (member3 != this.thisMember)) && (customAttribute.Name == attr.Name))
                {
                    this.otherMember = member3;
                    break;
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Constructs an <see cref="T:System.Linq.IQueryable"/> object that can evaluate the query represented by a specified expression tree.
        /// </summary>
        /// <param name="expression">
        /// An expression tree that represents a LINQ query.
        /// </param>
        /// <returns>
        /// An <see cref="T:System.Linq.IQueryable"/> that can evaluate the query represented by the specified expression tree.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="ArgumentException">
        /// </exception>
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            Type elementType = TypeSystem.GetElementType(expression.Type);

            if (!typeof(IQueryable <>).MakeGenericType(elementType).IsAssignableFrom(expression.Type))
            {
                throw new ArgumentException("Invalid type expression", "expression");
            }

            return((IQueryable)Activator.CreateInstance(
                       typeof(ExtendedQuery <>).MakeGenericType(elementType),
                       new object[] { this.QueryExecutor, this.RootQuery, expression }));
        }
Exemple #21
0
 private void InitOther()
 {
     if (this.otherType == null)
     {
         Type type = this.isMany ? TypeSystem.GetElementType(this.thisMember.Type) : this.thisMember.Type;
         this.otherType            = this.thisMember.DeclaringType.Model.GetMetaType(type);
         this.otherKey             = (this.assocMap.OtherKey != null) ? MetaAssociationImpl.MakeKeys(this.otherType, this.assocMap.OtherKey) : this.otherType.IdentityMembers;
         this.otherKeyIsPrimaryKey = MetaAssociationImpl.AreEqual(this.otherKey, this.otherType.IdentityMembers);
         foreach (MetaDataMember member in this.otherType.DataMembers)
         {
             if ((member.IsAssociation && (member != this.thisMember)) && (member.MappedName == this.thisMember.MappedName))
             {
                 this.otherMember = member;
                 break;
             }
         }
     }
 }
        public TResult ExecuteAsync <TResult>(Expression expression, CancellationToken cancellationToken = default)
        {
            // Validate Generic Type is a Task (might need to be adjusted if we need to support ValueTasks as well)
            if (!IsGenericTaskType(typeof(TResult)))
            {
                throw new ArgumentException($"Type is expected to be a generic Task type, but was '{typeof(TResult)}') .");
            }

            var result         = Translate(expression);
            var uri            = new Uri(result.CommandText);
            var elementType    = TypeSystem.GetElementType(expression.Type);
            var enumerableType = typeof(IEnumerable <>).MakeGenericType(elementType);

            var methodToExecute = typeof(ResourceRetriever).GetMethods()
                                  .Single(method => method.Name == nameof(ResourceRetriever.RetrieveResource) && !method.IsGenericMethod);

            return((TResult)methodToExecute.Invoke(_resourceRetriever, new object[] { enumerableType, uri, cancellationToken }));
        }
Exemple #23
0
        /*protected override Expression VisitMemberAccess(MemberExpression m)
         * {
         *  Expression source;
         *  ColumnExpression column = m.Expression as ColumnExpression;
         *  if (column == null)
         *  {
         *      source = Visit(m.Expression);
         *  }
         *  else
         *  {
         *      source = Expression.Property(_row, column.Name);
         *  }
         *
         *  /*Type type = m.Type;
         *  if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
         *  {
         *      type = Nullable.GetUnderlyingType(m.Type);
         *  }
         *  return Convert(
         *      Expression.Call(source, _miGetValue, Expression.Constant(m.Member.Name)),
         *      m.Type);
         * }*/

        protected override Expression VisitProjection(ProjectionExpression projection)
        {
            return(new ProjectionBuilder().Build(projection));

            _sourceType = TypeSystem.GetElementType(projection.Source.From.Type);
            _row        = Expression.Parameter(_sourceType, _sourceType.Name);
            Expression body = Visit(projection.Projector);

            SelectExpression source    = (SelectExpression)Visit(projection.Source);
            Expression       projector = Visit(projection.Projector);

            if (source != projection.Source || projector != projection.Projector)
            {
                return(new ProjectionExpression(source, projector));
            }
            //return projection;
            return(Expression.Constant(5));
        }
        protected override Expression VisitConstant(ConstantExpression node)
        {
            object value = node.Value;

            switch (value)
            {
            case IQueryable query:
            {
                if (!_existingBuffersMap.TryGetValue(query, out GlslVariable variable))
                {
                    VulkanBuffer computeBuffer = QueryToComputeBuffer(value);
                    _ctx.Inputs.Add(computeBuffer);
                    variable = _shader.AddBuffer(computeBuffer.ElementType, true, _isBufferStartOfChain);
                    _existingBuffersMap.Add(query, variable);
                }
                _bufferVariables.Push(variable);
                break;
            }

            case Array array:
            {
                if (!_existingBuffersMap.TryGetValue(array, out GlslVariable variable))
                {
                    var computeBuffer = new VulkanBuffer(_device, array, TypeSystem.GetElementType(node.Type), ResourceDirection.CpuToGpu);
                    _ctx.Inputs.Add(computeBuffer);
                    variable = _shader.AddBuffer(computeBuffer.ElementType, true, _isBufferStartOfChain);
                    _existingBuffersMap.Add(array, variable);
                }
                _bufferVariables.Push(variable);
                break;
            }

            default:
            {
                if (value == null)
                {
                    throw new NotImplementedException();
                }
                _shader.Main.Append(value.GlslLiteral());
                break;
            }
            }
            return(node);
        }
Exemple #25
0
        private ProjectionExpression GetTableProjection(object value)
        {
            IQueryable       table            = value as IQueryable;
            ColumnExpression columnExpression = value as ColumnExpression;
            Type             elementType;

            if (table != null)
            {
                elementType = table.ElementType;
            }
            else if (columnExpression != null)
            {
                elementType = TypeSystem.GetElementType(columnExpression.Type);
            }
            else
            {
                throw new NotSupportedException(String.Format("'{0}' table is not supported!", value.GetType().Name));
            }
            string tableAlias  = GetNextAlias();
            string selectAlias = GetNextAlias();
            List <MemberBinding>     bindings = new List <MemberBinding>();
            List <ColumnDeclaration> columns  = new List <ColumnDeclaration>();

            foreach (MemberInfo mi in GetMappedMembers(elementType))
            {
                string columnName = GetColumnName(mi);
                Type   columnType = GetColumnType(mi);
                bindings.Add(Expression.Bind(mi, new ColumnExpression(columnType, selectAlias, columnName)));
                columns.Add(new ColumnDeclaration(columnName, new ColumnExpression(columnType, tableAlias, columnName)));
            }
            Expression projector  = Expression.MemberInit(Expression.New(elementType), bindings);
            Type       resultType = typeof(IEnumerable <>).MakeGenericType(elementType);

            return(new ProjectionExpression(
                       new SelectExpression(
                           resultType,
                           selectAlias,
                           columns,
                           table != null? (Expression) new TableExpression(resultType, tableAlias, GetTableName(table)) : columnExpression,
                           null
                           ),
                       projector
                       ));
        }
Exemple #26
0
        internal ILinqToSolrService GetSolrQuery(Expression expression)
        {
            var elementType = TypeSystem.GetElementType(expression.Type);

            Service.ElementType = elementType;
            var qt = new LinqToSolrQueryTranslator(Service);

#if PORTABLE || NETCORE
            expression = Evaluator.PartialEval(expression, e => e.NodeType != ExpressionType.Parameter && !typeof(IQueryable).GetTypeInfo().IsAssignableFrom(e.Type.GetTypeInfo()));
#else
            expression = Evaluator.PartialEval(expression, e => e.NodeType != ExpressionType.Parameter && !typeof(IQueryable).IsAssignableFrom(e.Type));
#endif

            Service.CurrentQuery           = Service.CurrentQuery ?? new LinqToSolrQuery();
            Service.CurrentQuery.FilterUrl = qt.Translate(BooleanVisitor.Process(expression));


            return(Service);
        }
Exemple #27
0
        internal override Expression VisitMemberAccess(MemberExpression m)
        {
            if (MetaPosition.AreSameMember(m.Member, this.association.ThisMember.Member))
            {
                Expression[] keyValues = GetKeyValues(this.Visit(m.Expression), this.association.ThisKey);
                return(Translator.WhereClauseFromSourceAndKeys(this.otherSouce, this.association.OtherKey.ToArray(), keyValues));
            }
            Expression exp = this.Visit(m.Expression);

            if (exp != m.Expression)
            {
                if (exp.Type != m.Expression.Type && m.Member.Name == "Count" && TypeSystem.IsSequenceType(exp.Type))
                {
                    return(Expression.Call(typeof(Enumerable), "Count", new Type[] { TypeSystem.GetElementType(exp.Type) }, exp));
                }
                return(Expression.MakeMemberAccess(exp, m.Member));
            }
            return(m);
        }
Exemple #28
0
            public TResult Execute <TResult>(Expression expression)
            {
                try
                {
                    IDbCommand cmd = this.connection.CreateCommand();
                    cmd.CommandText = new QueryTranslator().Translate(expression);
                    IDataReader reader      = cmd.ExecuteReader();
                    Type        elementType = TypeSystem.GetElementType(expression.Type);

                    return((TResult)Activator.CreateInstance(typeof(ObjectReader <>).MakeGenericType(elementType), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { reader }, null));
                }
                catch (Exception ex)
                {
                    throw new Exception($"查询报错{ex}");
                }
                finally
                {
                }
            }
Exemple #29
0
        /// <summary>
        /// Execute provider
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public override object _(Expression expression)
        {
            Type elementType  = TypeSystem.GetElementType(expression.Type);
            var  isEnumerable = elementType.Name == "IEnumerable`1";

            // IQueryable queryable = Activator.CreateInstance(typeof(Playlist<>).MakeGenericType(elementType), this, expression) as IQueryable;

            var queryParams = new QueryParamsTranslator().Translate(expression);

            var queryResult = Channels(queryParams as QueryParams).Select(item => new TvgMedia(item["name"].ToString(), item["uuid"].ToString())
            {
                Position = (int)item["number"]
            });

            return(Activator.CreateInstance(
                       typeof(Playlist <>).MakeGenericType(elementType),
                       BindingFlags.Instance | BindingFlags.Public, null,
                       new object[] { queryResult },
                       null));
        }
        public override object Execute(Expression expression)
        {
            Type elementType  = TypeSystem.GetElementType(expression.Type);
            var  isEnumerable = elementType.Name == "IEnumerable`1";

            var queryableElements      = GetAllFilesAndFolders(root);
            var treeCopier             = new ExpressionTreeModifier(queryableElements);
            var selectedMembersVisitor = new SelectedMembersVisitor();
            var newExpressionTree      = treeCopier.Visit(expression);

            selectedMembersVisitor.Visit(treeCopier.SelectExpression);
            //TODO: catch the functions : OrderBy, Take, first, Single
            var context = new TranslationContext <FileSystemElement>(queryableElements, treeCopier.WhereExpression as Expression <Func <FileSystemElement, bool> >, selectedMembersVisitor.Members);

            return(Activator.CreateInstance(
                       typeof(ObjectReader <>).MakeGenericType(elementType),
                       BindingFlags.Instance | BindingFlags.NonPublic, null,
                       new object[] { context },
                       null));
        }