Inheritance: Expression, IArgumentProvider
        protected override Expression VisitNew(NewExpression node)
        {
            var originalConstructorParameters = node.Arguments.Select(x => x.Type).ToList();
            var genericType = node.Constructor.DeclaringType.GetGenericTypeDefinition();
            var genericTypeParameters = genericType.GetTypeInfo().GenericTypeArguments.ToList();
            var originalGenericArgs = node.Constructor.DeclaringType.GetTypeInfo().GenericTypeArguments.ToList();

            if (genericTypeParameters.Count != _newGenericArgs.Length)
            {
                throw new InvalidOperationException("Wrong number of generic argument values specified. This type requires " + genericTypeParameters.Count + " generic type arguments");
            }
            for (int i = 0; i < _newGenericArgs.Length; i++)
            {
                var constraints = genericTypeParameters[i].GetTypeInfo().GetGenericParameterConstraints().ToList();
                foreach (var constraint in constraints)
                {
                    if (!constraint.GetTypeInfo().IsAssignableFrom(_newGenericArgs[i].GetTypeInfo()))
                    {
                        throw new InvalidOperationException("Generic type parameter " + i + " is constrained to type " + constraint + ". The supplied type " + _newGenericArgs[i] + " does not meet this constraint");
                    }
                }
            }

            result = genericType.MakeGenericType(_newGenericArgs.ToArray()).GetTypeInfo().DeclaredConstructors.Where(x => x == node.Constructor).Single();
            throw new VisitStoppedException();
        }
 public MemberInitExpression Update(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
 {
   Contract.Requires(newExpression != null);
   Contract.Requires(bindings != null);
   Contract.Ensures(Contract.Result<MemberInitExpression>() != null);
   return default(MemberInitExpression);
 }
        private object InvokeConstructor(NewExpression expression, object[] args, out int argumentCount)
        {
            object valueToSet;
            int nestedArgumentCount;

            argumentCount = 0;
            ArrayList argList = new ArrayList();

            int i = 0;
            foreach (var arg in expression.Arguments)
            {
                switch (arg.NodeType)
                {
                    case ExpressionType.New:
                        valueToSet = InvokeConstructor((NewExpression)arg, args.Skip(i).ToArray(), out nestedArgumentCount);
                        i += nestedArgumentCount;
                        break;

                    case ExpressionType.MemberInit:
                        valueToSet = InvokeMemberInitExpression((MemberInitExpression)arg,
                            args.Skip(i).ToArray(), out nestedArgumentCount);
                        i += nestedArgumentCount;
                        break;

                    default:
                        valueToSet = LinqUtil.ChangeType(args[i], arg.Type);
                        i++;
                        break;
                }
                argList.Add(valueToSet);
            }

            argumentCount = i;
            return expression.Constructor.Invoke(argList.ToArray());
        }
Example #4
0
        /// <summary>
        /// Converts the new invocation call into a select clause.
        /// </summary>
        /// <param name="newExpression">The new expression.</param>
        /// <returns></returns>
        public static SelectClause NewToSelectClause(System.Linq.Expressions.NewExpression newExpression)
        {
            var selectClause = new SelectClause();

            selectClause.IsDistinct     = false;
            selectClause.StreamSelector = StreamSelector.RSTREAM_ISTREAM_BOTH;
            selectClause.SelectList     = new List <SelectClauseElement>();

            foreach (var argExpression in newExpression.Arguments)
            {
                if (argExpression is MemberExpression)
                {
                    var memberExpression    = (MemberExpression)argExpression;
                    var propertyExpression  = MemberToSoda(memberExpression);
                    var selectClauseElement = new SelectClauseExpression(propertyExpression);
                    selectClause.SelectList.Add(selectClauseElement);
                }
                else
                {
                    throw new ArgumentException(
                              String.Format("Expression of type {0} is not supported", argExpression.NodeType));
                }
            }

            return(selectClause);
        }
        protected override Expression VisitNew(NewExpression node)
        {
            var newNode = (NewExpression)base.VisitNew(node);
            if (newNode.Type.IsGenericType
                && newNode.Type.GetGenericTypeDefinition() == typeof(HashSet<>)
                && newNode.Arguments.Count == 1
                && newNode.Arguments[0] is AccumulatorExpression
                && ((AccumulatorExpression)newNode.Arguments[0]).AccumulatorType == AccumulatorType.Push)
            {
                Guid correlationId = Guid.Empty;
                if (_groupMap == null || TryGetCorrelatedGroup(node.Arguments[0], out correlationId))
                {
                    Expression accumulator = new AccumulatorExpression(
                        newNode.Type,
                        AccumulatorType.AddToSet,
                        ((AccumulatorExpression)newNode.Arguments[0]).Argument);

                    if (_groupMap != null)
                    {
                        accumulator = new CorrelatedAccumulatorExpression(
                            correlationId,
                            (AccumulatorExpression)accumulator);
                    }

                    return accumulator;
                }
            }

            return newNode;
        }
 public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers)
 {
   Contract.Requires(newExpression != null);
   Contract.Requires(initializers != null);
   Contract.Ensures(Contract.Result<ListInitExpression>() != null);
   return default(ListInitExpression);
 }
        protected override Expression VisitNew(NewExpression node)
        {
            // specialize for DateTime
            if (FormatIfExprIsDateTime(node)) return node;

            // promising type initializer(goto:VisitMemberInit)
            if (!node.Type.IsAnonymousType()) return node;

            var indent = BuildIndent();
            var innerTranslator = new BigQueryTranslateVisitor(depth, indentSize);

            var merge = node.Members.Zip(node.Arguments, (x, y) =>
            {
                var rightValue = innerTranslator.VisitAndClearBuffer(y);

                if (x.Name == rightValue.Trim('[', ']')) return "[" + x.Name + "]";

                return rightValue + " AS " + "[" + x.Name + "]";
            });

            var command = string.Join("," + Environment.NewLine,
                merge.Select(x => indent + x));

            sb.Append(command);

            return node;
        }
        protected override Expression VisitNew(NewExpression nex)
        {
            nex = (NewExpression)base.VisitNew(nex);

            var instance = (Expression)null;
            var method = (MethodBase)null;
            return Matcher
                .For(nex)
                    .Type(t => t.IsSubclassOf<Delegate>())
                    .Argument(0).AssignTo(out instance)

                .For(nex)
                    .Argument(1).As<AddressOfExpression>()
                        .Do(x => method = x.Method)

                .IfMatched<Expression>(
                    () => Expression.Call(null, CreateDelegateMethodInfo, new[] {
                        Expression.Constant(nex.Type),
                        instance,
                        Expression.Constant(method),
                        Expression.Constant(true)
                    }).Convert(nex.Type),
                    nex
                );
        }
        public LetSelectExpressionNode(MethodCallExpressionParseInfo parseInfo, LambdaExpression selector)
            : base(Utils.CheckNotNull("parseInfo", parseInfo), Utils.CheckNotNull("selector", selector))
        {
            // Heuristically detect "let" constructs
            // Assume a Select call is a "let" construct if its selector looks like this: <x> => new { <x> = <x>, <y> = ... }
            var selectorBody = selector.Body as NewExpression;
            if (selectorBody != null
                && selectorBody.Arguments.Count == 2
                && selectorBody.Arguments[0] == selector.Parameters[0]
                //&& selectorBody.Constructor.DeclaringType.IsDefined(typeof(CompilerGeneratedAttribute), false)
                && selectorBody.Members != null
                && selectorBody.Members.Count == 2)
            {
                _letConstruction = selectorBody;

                _resolvedAdaptedSelector = new ResolvedExpressionCache<Expression>(this);
                _resolvedLetExpression = new ResolvedExpressionCache<Expression>(this);
            }
            else
            {
                _letConstruction = null;

                _resolvedAdaptedSelector = null;
                _resolvedLetExpression = null;
            }
        }
        protected override Expression VisitNew(NewExpression newExpression)
        {
            Check.NotNull(newExpression, nameof(newExpression));

            var newNewExpression = base.VisitNew(newExpression);

            var selectExpression = QueryModelVisitor.TryGetQuery(_querySource);

            if (selectExpression != null)
            {
                for (var i = 0; i < newExpression.Arguments.Count; i++)
                {
                    var aliasExpression
                        = selectExpression.Projection
                            .OfType<AliasExpression>()
                            .SingleOrDefault(ae => ae.SourceExpression == newExpression.Arguments[i]);

                    if (aliasExpression != null)
                    {
                        aliasExpression.SourceMember
                            = newExpression.Members?[i]
                              ?? (newExpression.Arguments[i] as MemberExpression)?.Member;
                    }
                }
            }

            return newNewExpression;
        }
Example #11
0
        /// <summary>
        /// Returns a factory method that calls a default constructor of a type T.
        /// </summary>
        public static Func <T> GenerateFactory <T>() where T : new()
        {
            Expression <Func <T> > expr = () => new T();

            System.Linq.Expressions.NewExpression newExpr = (System.Linq.Expressions.NewExpression)expr.Body;

            var method = new DynamicMethod(
                name: "lambda",
                returnType: newExpr.Type,
                parameterTypes: new Type[0],
                m: typeof(DynamicModuleLambdaCompiler).Module,
                skipVisibility: true);

            ILGenerator ilGen = method.GetILGenerator();

            // Constructor for value types could be null
            if (newExpr.Constructor != null)
            {
                ilGen.Emit(OpCodes.Newobj, newExpr.Constructor);
            }
            else
            {
                LocalBuilder temp = ilGen.DeclareLocal(newExpr.Type);
                ilGen.Emit(OpCodes.Ldloca, temp);
                ilGen.Emit(OpCodes.Initobj, newExpr.Type);
                ilGen.Emit(OpCodes.Ldloc, temp);
            }

            ilGen.Emit(OpCodes.Ret);

            return((Func <T>)method.CreateDelegate(typeof(Func <T>)));
        }
        /// <summary>
        /// Visits new object expression like new DateTime().
        /// </summary>
        /// <param name="node">Node to visit.</param>
        /// <returns>Original node.</returns>
        protected override Expression VisitNew(NewExpression node)
        {
            var newObject = node.Constructor.Invoke(node.Arguments.Select(a => ((ConstantExpression)a).Value).ToArray());
            PrintConstant(newObject);

            return node;
        }
 /// <summary>
 /// Constructor with an <see cref="NewExpression"/> and an <see cref="ExpressionConverter"/>.
 /// </summary>
 /// <param name="expression">The original, not serializable <see cref="Expression"/>.</param>
 /// <param name="expConverter">The <see cref="ExpressionConverter"/> to convert contained <see cref="Expression">Expressions</see>.</param>
 public SerializableNewExpression(NewExpression expression, ExpressionConverter expConverter)
     : base(expression, expConverter)
 {
     Arguments = expression.Arguments.MakeSerializableCollection<SerializableExpression>(expConverter);
     Members = InterLinqTypeSystem.Instance.GetCollectionOf<InterLinqMemberInfo>(expression.Members);
     Constructor = InterLinqTypeSystem.Instance.GetInterLinqVersionOf<InterLinqConstructorInfo>(expression.Constructor);
 }
Example #14
0
        static void Main(string[] args)
        {

            //int maxCount = 40000;
            //List<HotSpotEntities> collection = new List<HotSpotEntities>();
            //for (int i = 0; i < maxCount; i++)
            //{
            //    Console.WriteLine(string.Format("成功创建连接对象{0}", i));
            //    var db = new HotSpotEntities();
            //    db.Connection.Open();
            //    collection.Add(db);
            //}

            Expression<Func<int, bool>> exp1 = x => x > 5;
            Expression<Func<int, bool>> exp2 = x => x < 10;

            ParameterExpression y = Expression.Parameter(typeof(int), "y");
            var newExp = new NewExpression(y);
            var newexp1 = newExp.Replace(exp1.Body);
            var newexp2 = newExp.Replace(exp2.Body);
            var newbody = Expression.And(newexp1, newexp2);

            Expression<Func<int, bool>> res = Expression.Lambda<Func<int, bool>>(newbody, y);
            //将表达式树描述的lambda表达式编译为可执行代码,并生成表示该lambda表达式的委托
            Func<int, bool> del = res.Compile();
            Console.WriteLine(del(7));
            Console.ReadLine();

        }
 protected MemberInitExpression UpdateMemberInit(MemberInitExpression init, NewExpression nex, IEnumerable<MemberBinding> bindings)
 {
     if (nex != init.NewExpression || bindings != init.Bindings) {
         return Expression.MemberInit(nex, bindings);
     }
     return init;
 }
 protected ListInitExpression UpdateListInit(ListInitExpression init, NewExpression nex, IEnumerable<ElementInit> initializers)
 {
     if (nex != init.NewExpression || initializers != init.Initializers) {
         return Expression.ListInit(nex, initializers);
     }
     return init;
 }
Example #17
0
 public MetaTableExpression(NewExpression newExpression, IList<SqlExpression> values)
     : base(SqlExpressionType.MetaTable, newExpression.Type)
 {
     SourceExpression = newExpression;
       Values = values;
       foreach(var v in Values)
     Operands.Add(v);
 }
Example #18
0
 //CONFORMING
 public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers) {
     if (addMethod == null) {
         return ListInit(newExpression, initializers as IEnumerable<Expression>);
     }
     ContractUtils.RequiresNotNull(newExpression, "newExpression");
     ContractUtils.RequiresNotNull(initializers, "initializers");
     return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>);
 }
        protected override Expression VisitNew(NewExpression nex)
        {
            nex = (NewExpression)base.VisitNew(nex);
            if (!nex.Constructor.DeclaringType.IsGenericTypeDefinedAs(typeof(Nullable<>)))
                return nex;

            return Expression.Convert(nex.Arguments[0], nex.Type);
        }
Example #20
0
        protected override Expression VisitNew(NewExpression node)
        {
            var args = node.Arguments.Cast<ConstantExpression>().Select(c => c.Value).ToArray();
            var value = node.Constructor.Invoke(args);
            var cex = Expression.Constant(value);

            return Visit(cex);
        }
 /// <summary>
 /// Creates a new expression that is like this one, but using the
 /// supplied children. If all of the children are the same, it will
 /// return this expression.
 /// </summary>
 /// <param name="newExpression">The <see cref="NewExpression"/> property of the result.</param>
 /// <param name="initializers">The <see cref="Initializers"/> property of the result.</param>
 /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
 public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers)
 {
     if (newExpression == NewExpression && initializers == Initializers)
     {
         return this;
     }
     return Expression.ListInit(newExpression, initializers);
 }
Example #22
0
 protected override NewExpression VisitNew(NewExpression nex)
 {
     if (nex.Arguments.Count == 0 && nex.Type.IsGenericType)
     {
         VisitConstant(Expression.Constant(null));
     }
     VisitExpressionList(nex.Arguments);
     return nex;
 }
        private static Node NewObject(NewExpression e)
        {
            string value = GetValue(e, false);

            return new ConstantNode
            {
                Text = value
            };
        }
Example #24
0
 protected static ListInitExpression UpdateListInit(ListInitExpression node, NewExpression nex,
                                                    IEnumerable<ElementInit> initializers)
 {
     if (node.NewExpression != nex || node.Initializers != initializers)
     {
         return Expression.ListInit(nex, initializers);
     }
     return node;
 }
 protected override Expression VisitNew(NewExpression node)
 {
     // Test if this is a nullable type
     if (IsNullable(node.Type) && node.Arguments.Count == 1)
     {
         return Expression.Convert(Visit(node.Arguments[0]), node.Type);
     }
     return base.VisitNew(node);
 }
 protected override Expression VisitNew(NewExpression n)
 {
     var replacedArguments = new List<Expression>();
     foreach (var argument in n.Arguments)
     {
         replacedArguments.Add(this.Visit(argument));
     }
     return Expression.New(n.Constructor, replacedArguments.ToArray());
 }
Example #27
0
 public static XmlNewExpression From(NewExpression nex)
 {
     return new XmlNewExpression
     {
         Method = XmlMetadataInfo.FromMetadata(nex.Constructor),
         Arguments = XmlExpression.FromMany(nex.Arguments),
         Members = XmlMetadataInfo.FromMany(nex.Members)
     };
 }
Example #28
0
        private static MemberInitExpression CreateMemberInitExpression(ParameterExpression left, Type entityType, Type dtoType, Tuple <Type, string>[] linkEntityNames)
        {
            System.Linq.Expressions.NewExpression newAnimal = System.Linq.Expressions.Expression.New(dtoType);

            List <MemberBinding> bindings = new List <MemberBinding>();
            var members = dtoType.GetProperties();//获取Dto的各个属性

            members.ToList().ForEach(p =>
            {
                try
                {
                    if (linkEntityNames != null && linkEntityNames.Length > 0)
                    {
                        var container = linkEntityNames.ToList().FirstOrDefault(x => p.Name.Contains(x.Item2));
                        if (container != null)
                        {
                            var rightStr = p.Name.Replace(container.Item2, "");

                            Expression right = Expression.Property(left, entityType.GetProperty(container.Item2));

                            MemberExpression mem = Expression.Property(right, rightStr);
                            //这里传的mem是 用 a.name给它赋值
                            System.Linq.Expressions.MemberBinding speciesMemberBinding = System.Linq.Expressions.Expression.Bind(p, mem);
                            bindings.Add(speciesMemberBinding);
                        }
                        else
                        {
                            MemberExpression mem = Expression.Property(left, p.Name);
                            //这里传的mem是 用 a.name给它赋值
                            System.Linq.Expressions.MemberBinding speciesMemberBinding = System.Linq.Expressions.Expression.Bind(p, mem);
                            bindings.Add(speciesMemberBinding);
                        }
                    }
                    else
                    {
                        try
                        {
                            MemberExpression mem = Expression.Property(left, p.Name);
                            //这里传的mem是 用 a.name给它赋值
                            System.Linq.Expressions.MemberBinding speciesMemberBinding = System.Linq.Expressions.Expression.Bind(p, mem);
                            bindings.Add(speciesMemberBinding);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch
                {
                }
            });

            System.Linq.Expressions.MemberInitExpression memberInitExpression = System.Linq.Expressions.Expression.MemberInit(newAnimal, bindings.ToArray());

            return(memberInitExpression);
        }
Example #29
0
 private IEnumerable<ColumnMap> ComputeColumnMaps(NewExpression newExpression)
 {
     for (var i = 0; i < newExpression.Members.Count; i++)
     {
         foreach (var _ in ComputeColumnMaps(newExpression.Arguments[i]).Select(_ => _.RightShift(newExpression.Members[i].Name)))
         {
             yield return _;
         }
     }
 }
        protected override Expression VisitNew(NewExpression node) {
            var arguments = node.Arguments.Cast<ParameterExpression>()
                                          .Select(a => Visit(a))
                                          .ToListOf<ParameterExpressionConfiguration>();

            return new NewExpressionConfiguration {
                arguments = arguments,
                type = node.Type.GetQualifiedName()
            };
        }
Example #31
0
 //CONFORMING
 public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers) {
     ContractUtils.RequiresNotNull(newExpression, "newExpression");
     ContractUtils.RequiresNotNull(initializers, "initializers");
     ReadOnlyCollection<Expression> initializerlist = initializers.ToReadOnly();
     if (initializerlist.Count == 0) {
         throw Error.ListInitializerWithZeroMembers();
     }
     MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     return ListInit(newExpression, addMethod, initializers);
 }
Example #32
0
 private NewExpression Convert(LinqExp.NewExpression linqNew)
 {
     return((linqNew.Members != null)
         ? Expression.New(
                linqNew.Constructor,
                Convert(linqNew.Arguments),
                linqNew.Members)
         : Expression.New(
                linqNew.Constructor,
                Convert(linqNew.Arguments)));
 }
        /// <summary>
        /// Visits new object expression (e.g. new DateTime()).
        /// </summary>
        /// <param name="node">Node to visit.</param>
        /// <returns>Original node.</returns>
        protected override Expression VisitNew(NewExpression node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }
            var newObject = node.Constructor.Invoke(node.Arguments.Select(a => ((ConstantExpression)a).Value).ToArray());
            PrintConstant(newObject);

            return node;
        }
Example #34
0
        public static void CreateMemberInitExpression()
        {
            System.Linq.Expressions.NewExpression newAnimal =
                System.Linq.Expressions.Expression.New(typeof(Animal));

            System.Reflection.MemberInfo speciesMember =
                typeof(Animal).GetMember("Species")[0];
            System.Reflection.MemberInfo ageMember =
                typeof(Animal).GetMember("Age")[0];

            // Create a MemberBinding object for each member
            // that you want to initialize.
            System.Linq.Expressions.MemberBinding speciesMemberBinding =
                System.Linq.Expressions.Expression.Bind(
                    speciesMember,
                    System.Linq.Expressions.Expression.Constant("horse"));
            System.Linq.Expressions.MemberBinding ageMemberBinding =
                System.Linq.Expressions.Expression.Bind(
                    ageMember,
                    System.Linq.Expressions.Expression.Constant(12));

            // Create a MemberInitExpression that represents initializing
            // two members of the 'Animal' class.
            System.Linq.Expressions.MemberInitExpression memberInitExpression =
                System.Linq.Expressions.Expression.MemberInit(
                    newAnimal,
                    speciesMemberBinding,
                    ageMemberBinding);


            //// Create a MemberInitExpression that represents initializing
            //// two members of the 'Animal' class.
            //System.Linq.Expressions.MemberInitExpression memberInitExpression =
            //    System.Linq.Expressions.Expression.MemberInit(
            //        newAnimal,
            //        speciesMemberBinding);

            Console.WriteLine(memberInitExpression.ToString());

            var expression = Expression.Lambda <Func <Dog, Animal> >(memberInitExpression);
            var compile    = expression.Compile();

            var dog = new Dog()
            {
                Species = "DOG"
            };

            var test = compile(dog);

            Console.WriteLine(test.ToJson());
            // This code produces the following output:
            //
            // new Animal() {Species = "horse", Age = 12}
        }
			protected override NewExpression VisitNew(NewExpression nex)
			{
				nex = DoVisitNew(nex);

				assignments.Add(new AssignmentInformation()
				{
					Declaration = nex,
					MembershipPath = membershipPath,
				});
				return nex;
			}
            private new RemoteLinq.NewExpression VisitNew(SystemLinq.NewExpression node)
            {
                IEnumerable <RemoteLinq.Expression>?arguments = null;

                if (node.Arguments?.Count > 0)
                {
                    arguments = node.Arguments
                                .Select(Visit)
                                .Select(Unwrap);
                }

                return(node.Constructor is null
                    ? new RemoteLinq.NewExpression(_typeInfoProvider.GetTypeInfo(node.Type))
                    : new RemoteLinq.NewExpression(_typeInfoProvider.GetConstructorInfo(node.Constructor), arguments, node.Members?.Select(x => _typeInfoProvider.GetMemberInfo(x))));
            }
Example #37
0
        /// <summary>
        /// 获取SelectLambda
        /// </summary>
        /// <returns></returns>
        public static System.Linq.Expressions.Expression <Func <T, V> > GetSelectLambda(Expression <Func <T, V> > selectEx = null)
        {
            ParameterExpression  param  = Expression.Parameter(typeof(T), "c");
            Expression           Iwhere = null;
            List <MemberBinding> mebers = new List <MemberBinding>();

            if (selectEx != null)
            {
                param  = selectEx.Parameters.FirstOrDefault();
                mebers = ((MemberInitExpression)selectEx.Body).Bindings.ToList();
            }
            System.Linq.Expressions.NewExpression newAnimal =
                System.Linq.Expressions.Expression.New(typeof(V));

            foreach (System.Reflection.PropertyInfo pinfo in typeof(V).GetProperties())
            {
                try
                {
                    if (mebers.Exists(s => s.Member.Name == pinfo.Name))
                    {
                        continue;
                    }
                    Expression valueEx = null;
                    object     ob      = pinfo.GetCustomAttributes(typeof(DataAttribute), false).FirstOrDefault();
                    object     ea      = pinfo.GetCustomAttributes(typeof(ChildTableAttribute), false).FirstOrDefault();
                    object     opAttr  = pinfo.GetCustomAttributes(typeof(OperationAttribute), false).FirstOrDefault();
                    System.Reflection.PropertyInfo TableInfo = null;
                    if (ea != null)
                    {
                        valueEx   = (ea as ChildTableAttribute).GetExpression(param, typeof(T));
                        TableInfo = (ea as ChildTableAttribute).getPropertyInfo(typeof(T));
                    }

                    MemberBinding Select = null;

                    if (ob != null || (opAttr != null && valueEx != null))
                    {
                        #region 存在子实体数据
                        //存在子实体数据
                        DataAttribute dataAtt = (DataAttribute)ob;
                        System.Reflection.MemberInfo Minfo = null;


                        if (TableInfo == null)
                        {
                            if (dataAtt.TableName != null)
                            {
                                TableInfo = typeof(T).GetProperty(dataAtt.TableName);
                            }
                            else
                            {
                                // 当前表别名处理无子从表
                                valueEx = Expression.Property(param, dataAtt.ColName);
                                if (valueEx.Type != pinfo.PropertyType)
                                {
                                    valueEx = Expression.Convert(valueEx, pinfo.PropertyType);
                                }
                                Select = Expression.Bind(pinfo, valueEx);
                                mebers.Add(Select);
                                continue;
                            }
                        }

                        //获取外键表类映射
                        if (TableInfo.PropertyType.IsGenericType && TableInfo.PropertyType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection <>))
                        {
                            #region 子从表外键
                            // 如果外键表是子从表
                            object op = pinfo.GetCustomAttributes(typeof(OperAttribute), false).FirstOrDefault();
                            if (op != null)
                            {
                                // 条件运算
                                OperAttribute opAtt = (OperAttribute)op;
                                // 统计表
                                Type tableType = BaseToolClass.GetObType(TableInfo.PropertyType);

                                // 分表实体
                                ParameterExpression paramd     = Expression.Parameter(tableType, "d");
                                Expression          whereRight = null;

                                if (ea != null)
                                {
                                    if (opAttr == null)
                                    {
                                        whereRight = (ob as ExpressAttrInterface).GetExpression(paramd, tableType);
                                    }
                                    else
                                    {
                                        whereRight = (opAttr as ExpressAttrInterface).GetExpression(paramd, tableType);
                                    }
                                }
                                else
                                {
                                    whereRight = Expression.Property(paramd, tableType.GetProperty(dataAtt.ColName));
                                }
                                // 筛选检索条件where
                                object[]   otList   = pinfo.GetCustomAttributes(typeof(OtherKeyAttribute), false);
                                Expression whereAll = null;
                                foreach (object ot in otList)
                                {
                                    OtherKeyAttribute otAtt     = (OtherKeyAttribute)ot;
                                    MemberExpression  whereLeft = Expression.Property(paramd, tableType.GetProperty(otAtt.CkColName));
                                    Expression        whereZ    = whereSymbol(otAtt.Symbol, whereLeft, null, otAtt.values);
                                    if (whereAll == null)
                                    {
                                        whereAll = whereZ;
                                    }
                                    else
                                    {
                                        whereAll = Expression.And(Iwhere, whereZ);
                                    }
                                }
                                //object otList1 = pinfo.GetCustomAttributes(typeof(SearchKeyAttribute), false);
                                //if (otList1 != null)
                                //{
                                //    SearchKeyAttribute otAtt = (SearchKeyAttribute)otList1;
                                //    int num = otAtt.Num;
                                //    for (int i = 0; i < num; i++)
                                //    {
                                //        MemberExpression whereLeft = Expression.Property(paramd, tableType.GetProperty(otAtt.ColName[i]));
                                //        Expression whereZ = whereSymbol(otAtt.Symbol[i], whereLeft, null, otAtt.Values[i]);
                                //        if (whereAll == null)
                                //        {
                                //            whereAll = whereZ;
                                //        }
                                //        else
                                //        {
                                //            whereAll = Expression.And(Iwhere, whereZ);
                                //        }
                                //    }
                                //}

                                System.Reflection.MethodInfo methInfo = BaseToolClass.GetMethodInfo(typeof(Expression), "Lambda", null, new Type[] { typeof(Expression), typeof(ParameterExpression[]) }, true);
                                object     Value      = methInfo.MakeGenericMethod(typeof(Func <,>).MakeGenericType(tableType, typeof(bool))).Invoke(null, new object[] { whereAll, new System.Linq.Expressions.ParameterExpression[] { paramd } });
                                Expression whereTable = valueEx;

                                var WhereExpression  = Expression.Lambda(whereAll, paramd);
                                var resultExpression = Expression.Call(null,
                                                                       BaseToolClass.GetMethodInfo(typeof(Enumerable), "Where", null, new Type[] { typeof(IEnumerable <TSource_1>), typeof(Func <TSource_1, bool>) }, true).MakeGenericMethod(tableType)
                                                                       , whereTable, WhereExpression);

                                // 统计属性
                                Expression syValue = null;

                                if (whereRight.Type != pinfo.PropertyType)
                                {
                                    whereRight = Expression.Convert(whereRight, pinfo.PropertyType);
                                }
                                syValue = Expression.Lambda(whereRight, paramd);


                                Type OType = pinfo.PropertyType;
                                if (opAtt.Symol == OperSymol.Count)
                                {
                                    OType = typeof(int);
                                }
                                whereTable = Expression.Call(
                                    null,
                                    BaseToolClass.GetMethodInfo(typeof(Enumerable), opAtt.ToMethodStr(), null, new Type[] { typeof(IEnumerable <TSource_1>), typeof(Func <,>).MakeGenericType(typeof(TSource_1), OType) }, true, OType).MakeGenericMethod(tableType),
                                    resultExpression,
                                    syValue
                                    );
                                Minfo   = pinfo;
                                valueEx = whereTable;
                                Select  = Expression.Bind(Minfo, valueEx);
                                mebers.Add(Select);
                            }

                            continue;
                            #endregion
                        }
                        else
                        {
                            // 如果外键表是外键关联表

                            if (valueEx == null)
                            {
                                valueEx = (ob as ExpressAttrInterface).GetExpression(param, typeof(T));
                            }
                            else
                            {
                                if (opAttr == null)
                                {
                                    if (ea != null)
                                    {
                                        valueEx = (ob as ExpressAttrInterface).GetExpression(valueEx, valueEx.Type);
                                    }
                                    else
                                    {
                                        valueEx = Expression.Property(valueEx, dataAtt.ColName);
                                    }
                                }
                                else
                                {
                                    valueEx = (opAttr as ExpressAttrInterface).GetExpression(valueEx, valueEx.Type);
                                }
                            }
                            Minfo = pinfo;
                        }
                        if (valueEx.Type != pinfo.PropertyType)
                        {
                            valueEx = Expression.Convert(valueEx, pinfo.PropertyType);
                        }
                        Select = Expression.Bind(Minfo, valueEx);
                        mebers.Add(Select);
                        #endregion
                    }
                    else
                    {
                        if (opAttr != null)
                        {
                            if (valueEx == null)
                            {
                                valueEx = (opAttr as ExpressAttrInterface).GetExpression(param, param.Type);
                            }
                            else
                            {
                                valueEx = (opAttr as ExpressAttrInterface).GetExpression(valueEx, valueEx.Type);
                            }
                        }
                        else
                        {
                            if (valueEx == null)
                            {
                                valueEx = Expression.Property(param, pinfo.Name);
                            }
                            else
                            {
                                valueEx = Expression.Property(valueEx, pinfo.Name);
                            }
                        }
                        if (valueEx.Type != typeof(V).GetProperty(pinfo.Name).PropertyType)
                        {
                            valueEx = Expression.Convert(valueEx, typeof(V).GetProperty(pinfo.Name).PropertyType);
                        }
                        mebers.Add(Expression.Bind(typeof(V).GetProperty(pinfo.Name), valueEx));
                    }
                }
                catch { }
            }
            Expression sel = Expression.MemberInit(newAnimal, mebers);
            return(Expression.Lambda <Func <T, V> >(sel, param));
        }
Example #38
0
 public MemberInitExpression Update(NewExpression newExpression, IEnumerable <MemberBinding> bindings)
 {
     throw new NotImplementedException();
 }
 public NewExpressionProxy(NewExpression node)
 {
     ContractUtils.RequiresNotNull(node, nameof(node));
     _node = node;
 }
Example #40
0
 /// <summary>Creates a <see cref="MemberInitExpression" />.</summary>
 /// <returns>
 ///     A <see cref="MemberInitExpression" /> that has the <see cref="NodeType" /> property equal to
 ///     <see cref="ExpressionType.MemberInit" /> and the <see cref="MemberInitExpression.NewExpression" /> and
 ///     <see cref="MemberInitExpression.Bindings" /> properties set to the specified values.
 /// </returns>
 /// <param name="newExpression">
 ///     A <see cref="NewExpression" /> to set the <see cref="MemberInitExpression.NewExpression" />
 ///     property equal to.
 /// </param>
 /// <param name="bindings">
 ///     An array of <see cref="MemberBinding" /> objects to use to populate the
 ///     <see cref="MemberInitExpression.Bindings" /> collection.
 /// </param>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="newExpression" /> or <paramref name="bindings" /> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 ///     The <see cref="MemberBinding.Member" /> property of an element of
 ///     <paramref name="bindings" /> does not represent a member of the type that <paramref name="newExpression" />.Type
 ///     represents.
 /// </exception>
 public static MemberInitExpression MemberInit(NewExpression newExpression, params MemberBinding[] bindings)
 {
     return(MemberInit(newExpression, (IEnumerable <MemberBinding>)bindings));
 }
Example #41
0
 internal MemberInitExpression(NewExpression newExpression, MemberBinding[] bindings)
 {
     NewExpression = newExpression;
     _bindings     = bindings;
     _bindingsAsReadOnlyCollection = ReadOnlyCollectionEx.Create(_bindings);
 }
Example #42
0
 internal ListInitExpression(NewExpression newExpression, ElementInit[] initializers)
 {
     _newExpression = newExpression;
     _initializers  = new TrueReadOnlyCollection <ElementInit>(initializers);
 }
Example #43
0
 protected internal override Expression VisitNew(NewExpression node)
 {
     Out(".New " + node.Type.ToString());
     VisitExpressions('(', node.Arguments);
     return(node);
 }
Example #44
0
 /// <summary>
 /// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
 /// </summary>
 /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
 /// <param name="initializers">An array that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
 /// <returns>
 /// A <see cref="ListInitExpression"/> that has the <see cref="P:Expressions.NodeType"/> property equal to ListInit
 /// and the <see cref="P:ListInitExpression.NewExpression"/> and <see cref="P:ListInitExpression.Initializers"/> properties set to the specified values.
 /// </returns>
 /// <remarks>
 /// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
 /// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
 /// </remarks>
 public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
 {
     return(ListInit(newExpression, (IEnumerable <ElementInit>)initializers));
 }
Example #45
0
 /// <summary>
 /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
 /// </summary>
 /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
 /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
 /// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
 /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
 public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers)
 {
     return(ListInit(newExpression, addMethod, initializers as IEnumerable <Expression>));
 }
Example #46
0
 internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection <ElementInit> initializers)
 {
     _newExpression = newExpression;
     _initializers  = initializers;
 }
Example #47
0
 protected override NewExpression VisitNew(NewExpression nex) => InvokeEvent(NewVisited, nex, base.VisitNew);
Example #48
0
 /// <summary>
 /// These are static classes as far as we are concerned - so they should never be able to run.
 /// </summary>
 /// <param name="expression"></param>
 /// <param name="result"></param>
 /// <param name="gc"></param>
 /// <param name="context"></param>
 /// <param name="container"></param>
 /// <returns></returns>
 public System.Linq.Expressions.Expression ProcessNew(System.Linq.Expressions.NewExpression expression, out IValue result, IGeneratedQueryCode gc, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     throw new NotImplementedException();
 }
Example #49
0
 protected virtual void VisitNew(NewExpression nex)
 {
     this.VisitExpressionList(nex.Arguments);
 }
 internal MemberInitExpression(NewExpression new_expression, ReadOnlyCollection <MemberBinding> bindings)
     : base(ExpressionType.MemberInit, new_expression.Type)
 {
     this.new_expression = new_expression;
     this.bindings       = bindings;
 }
 protected override MSAst.Expression VisitNew(MSAst.NewExpression node)
 {
     return(VisitCall(base.VisitNew(node)));
 }
Example #52
0
        /// <summary>
        /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
        /// </summary>
        /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
        /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
        /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param>
        /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
        public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable <Expression> initializers)
        {
            if (addMethod == null)
            {
                return(ListInit(newExpression, initializers));
            }
            ContractUtils.RequiresNotNull(newExpression, "newExpression");
            ContractUtils.RequiresNotNull(initializers, "initializers");

            List <ElementInit> initList = null;

            ElementInit[] initArray = null;

            initializers = initializers.NullOrEmptyChecked
                           (
                () =>
            {
                throw Error.ListInitializerWithZeroMembers();
            },
                () => initList     = new List <ElementInit>(),
                count => initArray = new ElementInit[count]
                           );
            var enumerator = initializers.GetEnumerator();

            try
            {
                enumerator.MoveNext();
                var initializer = enumerator.Current;
                if (addMethod == null)
                {
                    return(ListInit(newExpression, initializers));
                }
                if (initList != null)
                {
                    initList.Add(ElementInit(addMethod, initializer));
                    while (enumerator.MoveNext())
                    {
                        initializer = enumerator.Current;
                        initList.Add(ElementInit(addMethod, initializer));
                    }
                    initArray = initList.ToArray();
                }
                else
                {
                    var index = 0;
                    initArray[index] = ElementInit(addMethod, initializer);
                    index++;
                    while (enumerator.MoveNext())
                    {
                        initializer      = enumerator.Current;
                        initArray[index] = ElementInit(addMethod, initializer);
                        index++;
                    }
                }
            }
            finally
            {
                enumerator.Dispose();
            }
            ValidateListInitArgs(newExpression.Type, initArray);
            return(new ListInitExpression(newExpression, initArray));
        }