System.Linq.Expressions.Expression.Parameter(System.Type)

Here are the examples of the csharp api System.Linq.Expressions.Expression.Parameter(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1009 Examples 7

19 View Source File : UpsertCommandBuilder.cs
License : MIT License
Project Creator : artiomchi

public UpsertCommandBuilder<TEnreplacedy> UpdateIf(Expression<Func<TEnreplacedy, bool>> condition)
        {
            if (condition == null)
                throw new ArgumentNullException(nameof(condition));
            if (_updateCondition != null)
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.CantCallMethodTwice, nameof(WhenMatched)));
            if (_queryOptions.NoUpdate)
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.CantCallMethodTwice, nameof(WhenMatched), nameof(NoUpdate)));

            _updateCondition =
                Expression.Lambda<Func<TEnreplacedy, TEnreplacedy, bool>>(
                    condition.Body,
                    condition.Parameters[0],
                    Expression.Parameter(typeof(TEnreplacedy)));
            return this;
        }

19 View Source File : ObjectReviser.cs
License : MIT License
Project Creator : AutoReviser

private void Visit(Expression left, Expression right)
            {
                Queue<Expression> path = Disreplacedemble(left);
                switch (path.Dequeue())
                {
                    case MemberExpression member
                    when member.Member is PropertyInfo property && path.Any():
                        ReviseArgument(property, reviser: value =>
                        {
                            Type propertyType = property.PropertyType;
                            LambdaExpression lambda = replacedembleLambda(
                                Parameter(type: propertyType),
                                leftPath: path,
                                right);
                            return Reviser.Revise(propertyType, value, lambda);
                        });
                        break;

                    case MemberExpression member
                    when member.Member is PropertyInfo property:
                        ReviseArgument(property, _ => right.Evaluate());
                        break;
                }
            }

19 View Source File : PredicateBuilder.cs
License : MIT License
Project Creator : alirezanet

public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
      {
         var parameter = Expression.Parameter(typeof (T));

         var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
         var left = leftVisitor.Visit(expr1.Body);

         var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
         var right = rightVisitor.Visit(expr2.Body);

         return Expression.Lambda<Func<T, bool>>(Expression.OrElse(left!, right!), parameter);
      }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> OrElse<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr2.Body);

            return Expression.Lambda<Func<T, bool>>(Expression.OrElse(left, right), parameter);
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu

public static Action<object, object> GetValueSetter([NotNull] this PropertyInfo @this)
        {
            return ReflectionDictionary.PropertyValueSetters.GetOrAdd(@this, prop =>
            {
                if (!prop.CanWrite)
                    return null;

                var obj = Expression.Parameter(typeof(object), "o");
                var value = Expression.Parameter(typeof(object));

                Debug.replacedert(@this.DeclaringType != null);

                // Note that we are using Expression.Unbox for value types and Expression.Convert for reference types
                var expr =
                    Expression.Lambda<Action<object, object>>(
                        Expression.Call(
                            @this.DeclaringType.IsValueType
                                ? Expression.Unbox(obj, @this.DeclaringType)
                                : Expression.Convert(obj, @this.DeclaringType),
                            @this.GetSetMethod(),
                            Expression.Convert(value, @this.PropertyType)),
                        obj, value);
                return expr.Compile();
            });
        }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

Expression EvalSchemaFunc(JSchema schema)
        {
            var p = Expression.Parameter(typeof(JToken));
            return Expression.Lambda<Func<JToken, bool>>(Eval(schema, p), p);
        }

19 View Source File : OwinCallContext.DisableResponseCompression.cs
License : Apache License 2.0
Project Creator : aspnet

[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Lazy static initialize must not throw.")]
        private static RemoveHeaderDel GetRemoveHeaderDelegate()
        {
            try
            {
                Type iis7WorkerType = typeof(HttpContext).replacedembly.GetType(IIS7WorkerRequestTypeName);
                MethodInfo methodInfo = iis7WorkerType.GetMethod("SetKnownRequestHeader", BindingFlags.NonPublic | BindingFlags.Instance);

                ParameterExpression workerParamExpr = Expression.Parameter(typeof(HttpWorkerRequest));
                UnaryExpression iis7WorkerParamExpr = Expression.Convert(workerParamExpr, iis7WorkerType);
                MethodCallExpression callExpr = Expression.Call(iis7WorkerParamExpr, methodInfo,
                    Expression.Constant(HttpWorkerRequest.HeaderAcceptEncoding),
                    Expression.Constant(null, typeof(string)), Expression.Constant(false));
                return Expression.Lambda<RemoveHeaderDel>(callExpr, workerParamExpr).Compile();
            }
            catch (Exception)
            {
                return null;
            }
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private Activator GetActivator(ConstructorInfo constructor)
        {
            var parameters = constructor.GetParameters();

            var parameterExpression = Expression.Parameter(typeof(object[]));
            var argumentExpressions = new Expression[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var indexExpression = Expression.Constant(i);
                var paramType = parameters[i].ParameterType;
                var arrayExpression = Expression.ArrayIndex(parameterExpression, indexExpression);
                var arrayConvertExpression = Expression.Convert(arrayExpression, paramType);
                argumentExpressions[i] = arrayConvertExpression;
            }

            var constructorExpression = Expression.New(constructor, argumentExpressions);
            var constructorConvertExpression = Expression.Convert(constructorExpression, typeof(object));
            var lambdaExpression = Expression.Lambda<Activator>(constructorConvertExpression, parameterExpression);
            var compiledExpression = lambdaExpression.Compile();
            return compiledExpression;
        }

19 View Source File : ServerHandler.cs
License : MIT License
Project Creator : azist

private Func<object, RequestMsg, object> getFBody(MethodInfo miContract)
            {
               var attr = miContract.GetCustomAttribute(typeof(ArgsMarshallingAttribute)) as ArgsMarshallingAttribute;
               if (attr==null) return null;

               var tReqMsg = attr.RequestMsgType;

                var pInstance = Expression.Parameter(typeof(object));
                var pMsg = Expression.Parameter(typeof(RequestMsg));
                var pCastMsg = Expression.Variable(tReqMsg);

                var exprArgs = new List<Expression>();
                var pars = miContract.GetParameters();
                for(var i=0; i<pars.Length; i++)
                {
                   var par = pars[i];
                   if (par.ParameterType.IsByRef || par.IsOut || par.ParameterType.IsGenericParameter)
                     throw new ServerContractException(StringConsts.GLUE_METHOD_SPEC_UNSUPPORTED_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, par.Name));

                   var fName = "MethodArg_{0}_{1}".Args(i, par.Name);
                   exprArgs.Add( Expression.Field(pCastMsg, fName) );
                }

               try
               {
                 var isVoid = miContract.ReturnType==typeof(void);

                 if (isVoid)
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                 Expression.Constant(null, typeof(object))
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
                 else
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Convert(
                                                    Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                    typeof(object)
                                                 )
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
               }
               catch(Exception error)
               {
                 throw new ServerContractException(StringConsts.GLUE_METHOD_ARGS_MARSHAL_LAMBDA_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, error.ToMessageWithType()), error);
               }
            }

19 View Source File : TypeUtil.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static Func<IntPtr, Type>? BuildGetTypeFromHandleFunc()
        {
            var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(IntPtr) }, null);
            if (method == null)
                return null;

            var param = Parameter(typeof(IntPtr));

            return Lambda<Func<IntPtr, Type>>(
                Call(method, param),
                param
            ).Compile();
        }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> OrElse<T, TNav>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<TNav, bool>> expr2,
            Expression<Func<T, TNav>> navigationProperty
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var navVisitor = new ReplaceExpressionVisitor(navigationProperty.Parameters[0], parameter);
            var nav = navVisitor.Visit(navigationProperty.Body); // Reset the navigation prop expression to start from the shared parameter
            var right = Expression.Invoke(expr2, nav); // Create an expression that navigates to the property

            return Expression.Lambda<Func<T, bool>>(Expression.OrElse(left, right), parameter);
        }

19 View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu

[CanBeNull]
        public static Action<object, object> GetValueSetter([NotNull] this PropertyInfo propertyInfo)
        {
            return CacheUtil.PropertyValueSetters.GetOrAdd(propertyInfo, prop =>
            {
                if (!prop.CanWrite)
                    return null;

                var obj = Expression.Parameter(typeof(object), "o");
                var value = Expression.Parameter(typeof(object));

                Debug.replacedert(propertyInfo.DeclaringType != null);

                // Note that we are using Expression.Unbox for value types and Expression.Convert for reference types
                var expr =
                    Expression.Lambda<Action<object, object>>(
                        Expression.Call(
                            propertyInfo.DeclaringType.IsValueType
                                ? Expression.Unbox(obj, propertyInfo.DeclaringType)
                                : Expression.Convert(obj, propertyInfo.DeclaringType),
                            propertyInfo.GetSetMethod(),
                            Expression.Convert(value, propertyInfo.PropertyType)),
                        obj, value);
                return expr.Compile();
            });
        }

19 View Source File : SqlQueryable.cs
License : MIT License
Project Creator : AlenToma

public ISqlQueryable<T> OrderByDescending(string columnName)
        {
            var prop = FastDeepCloner.DeepCloner.GetFastDeepClonerProperties(typeof(T)).FirstOrDefault(x => string.Equals(columnName, x.Name, StringComparison.CurrentCultureIgnoreCase));
            if (prop == null)
            {
                throw new EnreplacedyException($"T dose not containe property {columnName}");
            }
            var param = Expression.Parameter(typeof(T));
            var field = Expression.PropertyOrField(param, prop.Name);
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var funcType = typeof(Func<,>).MakeGenericType(typeof(T), prop.PropertyType);
            Expression exp = Expression.Lambda(funcType, field, param);
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderByDescending", new Type[] { typeof(T), prop.PropertyType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

19 View Source File : Engine.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr

public static Func<T, bool> CompileRule<T>(Expression r)
        {
            var paramUser = System.Linq.Expressions.Expression.Parameter(typeof(Operand));
            System.Linq.Expressions.Expression expr = BuildExpr<T>(r, paramUser);
            // build a lambda function User->bool and compile it
            var value = System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(expr, paramUser).Compile(true);
            return value;
        }

19 View Source File : QueryableExtension.cs
License : GNU General Public License v3.0
Project Creator : 2dust

static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty)
        {
            if (memberProperty.PropertyType != typeof(TProp)) throw new Exception();

            var thisArg = Expression.Parameter(typeof(T));
            var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg);

            return lamba;
        }

19 View Source File : ReflectionBenchmarks.cs
License : MIT License
Project Creator : asc-community

public static Func<T1, F1> FieldGetterDelegate<T1, F1>(string name)
		{
			FieldInfo fieldInfo = typeof(T1).GetField(name,
				BindingFlags.Instance |
				BindingFlags.Public |
				BindingFlags.NonPublic);
			ParameterExpression A = Expression.Parameter(typeof(T1));
			Expression BODY = Expression.Field(A, fieldInfo);
			return Expression.Lambda<Func<T1, F1>>(BODY, A).Compile();
		}

19 View Source File : PropertyExpressionBuilder.cs
License : MIT License
Project Creator : alethic

IEnumerable<Expression> BuildPropertiesAll(JSchemaExpressionBuilder builder, JSchema schema, Expression o)
        {
            if (schema.Properties.Count > 0)
                yield return IfThenElseTrue(
                    IsTokenType(o, JTokenType.Object),
                    AllOf(schema.Properties.Select(i =>
                        BuildProperty(builder, i.Key, i.Value, Expression.Convert(o, typeof(JObject))))));

            if (schema.PatternProperties.Count > 0)
                yield return IfThenElseTrue(
                    IsTokenType(o, JTokenType.Object),
                        AllOf(schema.PatternProperties.Select(i =>
                            BuildPatternProperty(builder, i.Key, i.Value, Expression.Convert(o, typeof(JObject))))));

            if (schema.AllowAdditionalProperties == false)
            {
                yield return IfThenElseTrue(
                    IsTokenType(o, JTokenType.Object),
                    CallThis(
                        nameof(AllowAdditionalProperties),
                        Expression.Constant(schema),
                        Expression.Convert(o, typeof(JObject))));
            }
            else if (schema.AdditionalProperties != null)
            {
                var p = Expression.Parameter(typeof(JToken));

                yield return IfThenElseTrue(
                    IsTokenType(o, JTokenType.Object),
                    CallThis(
                        nameof(AdditionalProperties),
                        Expression.Constant(schema),
                        Expression.Convert(o, typeof(JObject)),
                        EvalSchemaFunc(builder, schema.AdditionalProperties)));
            }
        }

19 View Source File : ImmutableArrayReviser.cs
License : MIT License
Project Creator : AutoReviser

private void Visit(Expression left, Expression right)
            {
                Queue<Expression> path = Disreplacedemble(left);
                var call = (MethodCallExpression)path.Dequeue();
                var index = (int)call.Arguments[0].Evaluate();
                if (path.Any())
                {
                    object element = _elements[index];
                    ParameterExpression parameter = Parameter(call.Type);
                    var lambda = replacedembleLambda(parameter, path, right);
                    var newElement = Reviser.Revise(call.Type, element, lambda);
                    _elements[index] = newElement;
                }
                else
                {
                    _elements[index] = right.Evaluate();
                }
            }

19 View Source File : DataFilterUtil.cs
License : MIT License
Project Creator : 2881099

internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
			if (scopedDataFilter != null) {
				SetRepositoryDataFilter(repos, null);
			}
			if (scopedDataFilter == null) {
				scopedDataFilter = _globalDataFilter;
			}
			if (scopedDataFilter == null) return;
			using (var globalFilter = new FluentDataFilter()) {
				scopedDataFilter(globalFilter);

				var type = repos.GetType();
				Type enreplacedyType = (repos as IBaseRepository).EnreplacedyType;
				if (enreplacedyType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");

				var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
				var newFilter = new Dictionary<string, LambdaExpression>();
				foreach (var gf in globalFilter._filters) {
					if (notExists.ContainsKey(gf.name)) continue;

					LambdaExpression newExp = null;
					var filterParameter1 = Expression.Parameter(enreplacedyType, gf.exp.Parameters[0].Name);
					try {
						newExp = Expression.Lambda(
							typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)),
							new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
							filterParameter1
						);
					} catch {
						notExists.TryAdd(gf.name, true); //防止第二次错误
						continue;
					}
					newFilter.Add(gf.name, newExp);
				}
				if (newFilter.Any() == false) return;

				var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
					var reposParameter = Expression.Parameter(type);
					var nameParameter = Expression.Parameter(typeof(string));
					var expressionParameter = Expression.Parameter(
						typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)))
					);
					return Expression.Lambda(
						Expression.Block(
							Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
						),
						new[] {
						reposParameter, nameParameter, expressionParameter
						}
					).Compile();
				});
				foreach (var nf in newFilter) {
					del.DynamicInvoke(repos, nf.Key, nf.Value);
				}
				newFilter.Clear();
			}
		}

19 View Source File : StreamerFormats.cs
License : MIT License
Project Creator : azist

private Action<TWriter, object> compileWriter(Type tp, MethodInfo miWrite)
          {
              var pWritingStreamer = Expression.Parameter(typeof(TWriter));
              var pValue = Expression.Parameter(typeof(object));
              return Expression.Lambda<Action<TWriter, object>>(
                              Expression.Call(pWritingStreamer, miWrite,
                                                Expression.Convert( pValue, tp)
                                              ),
                              pWritingStreamer, pValue).Compile();
          }

19 View Source File : ExpressionLogicalOperatorsExtension .cs
License : MIT License
Project Creator : AlphaYu

public static Expression<Func<T, bool>> Or<T>([NotNull] this Expression<Func<T, bool>> @this, Expression<Func<T, bool>> expr)
        {
            var parameter = Expression.Parameter(typeof(T));

            var leftVisitor = new ReplaceExpressionVisitor(@this.Parameters[0], parameter);
            var left = leftVisitor.Visit(@this.Body);
            var rightVisitor = new ReplaceExpressionVisitor(expr.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr.Body);

            return Expression.Lambda<Func<T, bool>>(
                Expression.OrElse(left, right), parameter);
        }

19 View Source File : ExpressionLogicalOperatorsExtension .cs
License : MIT License
Project Creator : AlphaYu

public static Expression<Func<T, bool>> And<T>([NotNull] this Expression<Func<T, bool>> @this, Expression<Func<T, bool>> expr)
        {
            var parameter = Expression.Parameter(typeof(T));

            var leftVisitor = new ReplaceExpressionVisitor(@this.Parameters[0], parameter);
            var left = leftVisitor.Visit(@this.Body);
            var rightVisitor = new ReplaceExpressionVisitor(expr.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr.Body);

            return Expression.Lambda<Func<T, bool>>(
                Expression.AndAlso(left, right), parameter);
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
    {
        if (enreplacedy == null) return;
        if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();

        if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
        {
            if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
            {
                prop.SetValue(enreplacedy, value, null);
                return;
            }
            if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
            {
                field.SetValue(enreplacedy, value);
                return;
            }
            throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
        }

        Action<object, string, object> func = null;
        try
        {
            func = _dicSetPropertyOrFieldValue
                .GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyName, pn =>
                {
                    var t = enreplacedyType;
                    MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                            Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    if (memberinfo != null)
                    {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberinfo),
                                Expression.Convert(
                                    parm3,
                                    memberinfo.GetPropertyOrFieldType()
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                });
        }
        catch
        {
            System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
            SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
            return;
        }
        func(enreplacedy, propertyName, value);
    }

19 View Source File : HttpContextUtility.cs
License : MIT License
Project Creator : AlphaYu

public static HttpContext GetCurrentHttpContext()
        {
            var asyncLocal = (_asyncLocalAccessor ??= CreateAsyncLocalAccessor())();
            if (asyncLocal == null)
            {
                return null;
            }

            var holder = (_holderAccessor ??= CreateHolderAccessor(asyncLocal))(asyncLocal);
            if (holder == null)
            {
                return null;
            }

            return (_httpContextAccessor ??= CreateHttpContextAccessor(holder))(holder);

            static Func<object> CreateAsyncLocalAccessor()
            {
                var fieldInfo = typeof(HttpContextAccessor).GetField("_httpContextCurrent", BindingFlags.Static | BindingFlags.NonPublic);
                var field = Expression.Field(null, fieldInfo);
                return Expression.Lambda<Func<object>>(field).Compile();
            }

            static Func<object, object> CreateHolderAccessor(object asyncLocal)
            {
                var holderType = asyncLocal.GetType().GetGenericArguments()[0];
                var method = typeof(AsyncLocal<>).MakeGenericType(holderType).GetProperty("Value").GetGetMethod();
                var target = Expression.Parameter(typeof(object));
                var convert = Expression.Convert(target, asyncLocal.GetType());
                var getValue = Expression.Call(convert, method);
                return Expression.Lambda<Func<object, object>>(getValue, target).Compile();
            }

            static Func<object, HttpContext> CreateHttpContextAccessor(object holder)
            {
                var target = Expression.Parameter(typeof(object));
                var convert = Expression.Convert(target, holder.GetType());
                var field = Expression.Field(convert, "Context");
                var convertAsResult = Expression.Convert(field, typeof(HttpContext));
                return Expression.Lambda<Func<object, HttpContext>>(convertAsResult, target).Compile();
            }
        }

19 View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider

private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
                (ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
                    .Select(item => (Expression.Parameter(typeof(object)), item))
                    .ToArray();

                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo,
                            argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
                        argObjectParameters.Select(item => item.expression))
                    .Compile();

                return method;
            }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> Or<T, TNav>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<TNav, bool>> expr2,
            Expression<Func<T, TNav>> navigationProperty
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var navVisitor = new ReplaceExpressionVisitor(navigationProperty.Parameters[0], parameter);
            var nav = navVisitor.Visit(navigationProperty.Body); // Reset the navigation prop expression to start from the shared parameter
            var right = Expression.Invoke(expr2, nav); // Create an expression that navigates to the property

            return Expression.Lambda<Func<T, bool>>(Expression.Or(left, right), parameter);
        }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> AndAlso<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr2.Body);

            return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left, right), parameter);
        }

19 View Source File : SqlQueryable.cs
License : MIT License
Project Creator : AlenToma

public ISqlQueryable<T> OrderBy(string columnName)
        {
            var prop = FastDeepCloner.DeepCloner.GetFastDeepClonerProperties(typeof(T)).FirstOrDefault(x => string.Equals(columnName, x.Name, StringComparison.CurrentCultureIgnoreCase));
            if (prop == null)
            {

                throw new EnreplacedyException($"T dose not containe property {columnName}");
            }
            var param = Expression.Parameter(typeof(T));
            var field = Expression.PropertyOrField(param, prop.Name);
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var funcType = typeof(Func<,>).MakeGenericType(typeof(T), prop.PropertyType);
            Expression exp = Expression.Lambda(funcType, field, param);
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderBy", new Type[] { typeof(T), prop.PropertyType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> Or<T>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
            var right = rightVisitor.Visit(expr2.Body);

            return Expression.Lambda<Func<T, bool>>(Expression.Or(left, right), parameter);
        }

19 View Source File : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyValue(Type sourceType, object source, string propertyOrField, object value)
        {
            if (source == null) return;
            if (sourceType == null) sourceType = source.GetType();
            _dicSetEnreplacedyValueWithPropertyName
                .GetOrAdd(sourceType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyOrField, pf =>
                {
                    var t = sourceType;
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                        Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    var memberInfos = t.GetMember(pf, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.MemberType == MemberTypes.Field || a.MemberType == MemberTypes.Property);
                    foreach (var memberInfo in memberInfos) {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberInfo),
                                Expression.Convert(
                                    parm3,
                                    memberInfo.MemberType == MemberTypes.Field ? (memberInfo as FieldInfo)?.FieldType : (memberInfo as PropertyInfo)?.PropertyType
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                })(source, propertyOrField, value);
        }

19 View Source File : EventToCommandBehavior.cs
License : MIT License
Project Creator : anjoy8

private void AddEventHandler(EventInfo eventInfo, object item, Action<object, EventArgs> action)
        {
            var eventParameters = eventInfo.EventHandlerType
                .GetRuntimeMethods().First(m => m.Name == "Invoke")
                .GetParameters()
                .Select(p => Expression.Parameter(p.ParameterType))
                .ToArray();

            var actionInvoke = action.GetType()
                .GetRuntimeMethods().First(m => m.Name == "Invoke");

            _handler = Expression.Lambda(
                eventInfo.EventHandlerType,
                Expression.Call(Expression.Constant(action), actionInvoke, eventParameters[0], eventParameters[1]),
                eventParameters
            )
            .Compile();

            eventInfo.AddEventHandler(item, _handler);
        }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

public Expression Eval(JSchema schema, Expression token)
        {
            // ensure we are working with the final referenced schema
            while (schema.Ref != null && schema.Ref != schema)
                schema = schema.Ref;

            // evaluating of this schema is already in progress, return future variable to delegate
            if (delayed.TryGetValue(schema, out var expr))
            {
                // we are recursed, but have not yet allocated a variable, do so
                if (expr is null)
                    expr = delayed[schema] = Expression.Variable(typeof(Func<JToken, bool>));

                // return call to eventually populated delegate variable
                return Expression.Invoke(expr, token);
            }

            // insert null entry to detect future recursion
            delayed[schema] = null;

            // build the actual invocation of the validation
            var parm = Expression.Parameter(typeof(JToken));
            var body = BuildSchemaBody(schema, parm);
            var func = Expression.Lambda<Func<JToken, bool>>(body, parm);

            // we did recurse, store away our finished lambda
            if (delayed.TryGetValue(schema, out var expr2) && expr2 != null)
            {
                compile[schema] = func;
                return Expression.Invoke(expr2, token);
            }

            // was never actually recursed, remove
            if (delayed[schema] == null)
                delayed.Remove(schema);

            // return invocation of validator
            return Expression.Invoke(func, token);
        }

19 View Source File : UpsertCommandBuilder.cs
License : MIT License
Project Creator : artiomchi

public UpsertCommandBuilder<TEnreplacedy> WhenMatched(Expression<Func<TEnreplacedy, TEnreplacedy>> updater)
        {
            if (updater == null)
                throw new ArgumentNullException(nameof(updater));
            if (_updateExpression != null)
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.CantCallMethodTwice, nameof(WhenMatched)));
            if (_queryOptions.NoUpdate)
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.CantCallMethodTwice, nameof(WhenMatched), nameof(NoUpdate)));

            _updateExpression =
                Expression.Lambda<Func<TEnreplacedy, TEnreplacedy, TEnreplacedy>>(
                    updater.Body,
                    updater.Parameters[0],
                    Expression.Parameter(typeof(TEnreplacedy)));
            return this;
        }

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : ReflectionBenchmarks.cs
License : MIT License
Project Creator : asc-community

internal static object Do(object instance, string field)
			{
				Type type = instance.GetType();
				if (Delegates.TryGetValue((type, field), out var cachedGet))
				{
					return cachedGet(instance);
				}
				FieldInfo fieldInfo = type.GetField(field,
					BindingFlags.Instance |
					BindingFlags.Public |
					BindingFlags.NonPublic);
				ParameterExpression A = Expression.Parameter(typeof(object));
				Expression BODY = Expression.Convert(Expression.Field(Expression.Convert(A, type), fieldInfo), typeof(object));
				var newGet = Expression.Lambda<Func<object, object>>(BODY, A).Compile();
				Delegates.Add((type, field), newGet);
				return newGet(instance);
			}

19 View Source File : ExpressionBuilderBase.cs
License : MIT License
Project Creator : alethic

protected Expression EvalSchemaFunc(JSchemaExpressionBuilder builder, JSchema schema)
        {
            var p = Expression.Parameter(typeof(JToken));
            return Expression.Lambda<Func<JToken, bool>>(builder.Eval(schema, p), p);
        }

19 View Source File : ModuleInfo.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private static CommandInfo.CommandHandlerDelegate BuildCommandHandler(Type type, MethodInfo method)
        {
            var moduleParameter = Expression.Parameter(typeof(object));
            var convertedModuleParameter = Expression.Convert(moduleParameter, type);
            var commandParameter = Expression.Parameter(typeof(ICommand));
            var loggerParameter = Expression.Parameter(typeof(ILogger));
            var ctParameter = Expression.Parameter(typeof(CancellationToken));

            var parameters = method.GetParameters().Select(x => x.ParameterType).ToList();
            MethodCallExpression call;
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter, ctParameter);
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, ctParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter);
            else
                throw new ArgumentException($"Invalid method signature of command {method.Name} on type {type}.");

            var lambda = Expression.Lambda<CommandInfo.CommandHandlerDelegate>(call, moduleParameter, commandParameter, loggerParameter, ctParameter);

            return lambda.Compile();
        }

19 View Source File : RepositoryBase.cs
License : MIT License
Project Creator : a34546

protected static Expression<Func<TEnreplacedy, bool>> CreateEqualityExpressionForId(TPrimaryKey id)
        {
            var lambdaParam = Expression.Parameter(typeof(TEnreplacedy));

            var lambdaBody = Expression.Equal(
                Expression.PropertyOrField(lambdaParam, "Id"),
                Expression.Constant(id, typeof(TPrimaryKey))
            );

            return Expression.Lambda<Func<TEnreplacedy, bool>>(lambdaBody, lambdaParam);
        }

19 View Source File : Argument.cs
License : MIT License
Project Creator : AutoReviser

private static object CastIfNeeded(object value, Type type)
        {
            if (value == null)
            {
                return value;
            }

            if (value.GetType() == type)
            {
                return value;
            }

            // TODO: Cache the lambda Delegate.
            ParameterExpression parameter = Expression.Parameter(value.GetType());
            UnaryExpression body = Expression.Convert(parameter, type);
            LambdaExpression lambda = Expression.Lambda(body, parameter);
            return lambda.Compile().DynamicInvoke(value);
        }

19 View Source File : GridifyMapper.cs
License : MIT License
Project Creator : alirezanet

private static Expression<Func<T, object>> CreateExpression(string from)
      {
         // x =>
         var parameter = Expression.Parameter(typeof(T));
         // x.Name
         var mapProperty = Expression.Property(parameter, from);
         // (object)x.Name
         var convertedExpression = Expression.Convert(mapProperty, typeof(object));
         // x => (object)x.Name
         return Expression.Lambda<Func<T, object>>(convertedExpression, parameter);
      }

19 View Source File : ImmutableDictionaryReviser.cs
License : MIT License
Project Creator : AutoReviser

private static (MethodCallExpression call, LambdaExpression lambda) Refactor(
            Expression left, Expression right)
        {
            Queue<Expression> path = Disreplacedemble(left);
            var call = (MethodCallExpression)path.Dequeue();
            ParameterExpression parameter = Parameter(call.Type);
            return (call, lambda: replacedembleLambda(parameter, path, right));
        }

19 View Source File : NativeDecimalGetterHelper.cs
License : MIT License
Project Creator : 1996v

private static Func<Decimal, DecimalBinaryBits> Build()
        {
            ParameterExpression de = Expression.Parameter(typeof(Decimal));
            Expression low, mid, high, flags;
            try
            {
                //FRAMEWORK
                low = Expression.Field(de, typeof(Decimal).GetField("lo", BindingFlags.Instance | BindingFlags.NonPublic));
                mid = Expression.Field(de, typeof(Decimal).GetField("mid", BindingFlags.Instance | BindingFlags.NonPublic));
                high = Expression.Field(de, typeof(Decimal).GetField("hi", BindingFlags.Instance | BindingFlags.NonPublic));
                flags = Expression.Field(de, typeof(Decimal).GetField("flags", BindingFlags.Instance | BindingFlags.NonPublic));
            }
            catch
            {
                try
                {
                    low = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Low", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    mid = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Mid", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    high = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("High", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    flags = Expression.Field(de, typeof(Decimal).GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic));
                }
                catch (Exception ex)
                {
                    throw BssomSerializationTypeFormatterException.TypeFormatterError(typeof(decimal), ex.Message);
                }
            }

            NewExpression body = Expression.New(typeof(DecimalBinaryBits).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }), low, mid, high, flags);
            return Expression.Lambda<Func<Decimal, DecimalBinaryBits>>(body, de).Compile();
        }

19 View Source File : StreamerFormats.cs
License : MIT License
Project Creator : azist

private Func<TReader, object> compileReader(Type tp, MethodInfo miRead)
          {
              var pReadingStreamer = Expression.Parameter(typeof(TReader));
              return Expression.Lambda<Func<TReader, object>>(
                              Expression.Convert(  Expression.Call(pReadingStreamer, miRead), typeof(object)  ),
                              pReadingStreamer).Compile();
          }

19 View Source File : PredicateBuilder.cs
License : MIT License
Project Creator : alirezanet

public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
      {
         var parameter = Expression.Parameter(typeof (T));

         var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
         var left = leftVisitor.Visit(expr1.Body);

         var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
         var right = rightVisitor.Visit(expr2.Body);

         return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left!, right!), parameter);
      }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private ParameterResolver[] GetParameterResolvers(Type type, ConstructorInfo constructor)
        {
            var properties = GetInstanceProperties(type);
            var parameters = constructor.GetParameters();

            var parameterResolvers = new ParameterResolver[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];

                var property = FindProperty(type, parameter, properties);

                var parameterExpression = Expression.Parameter(typeof(object));
                var parameterConvertExpression = Expression.Convert(parameterExpression, type);
                var propertyExpression = Expression.Property(parameterConvertExpression, property);
                var propertyConvertExpression = Expression.Convert(propertyExpression, typeof(object));
                var lambdaExpression = Expression.Lambda<Func<object, object>>(propertyConvertExpression, parameterExpression);
                var compiledExpression = lambdaExpression.Compile();

                var parameterResolver = new ParameterResolver(parameter, property, compiledExpression);
                parameterResolvers[i] = parameterResolver;
            }

            return parameterResolvers;
        }

19 View Source File : MethodInvoker.cs
License : MIT License
Project Creator : 1100100

private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
            var instanceParameter = Expression.Parameter(typeof(object));
            var argsParameter = Expression.Parameter(typeof(object[]));

            var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));

            var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
            var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
            if (methodCaller.Type == typeof(Task))
            {
                var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
                return (instance, args) => { action(instance, args); return Task.CompletedTask; };
            }

            var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
            return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static void ConstructorInit(ConstructorInfo ctor)
        {
            ParameterInfo[] paras = ctor.GetParameters();
            ParameterExpression count = Expression.Parameter(typeof(int));
            Expression body;
            if (paras.Length == 0)
            {
                body = Expression.New(ctor);
            }
            else
            {
                body = Expression.New(ctor, count);
            }

            constructor = Expression.Lambda<Ctor>(body, CommonExpressionMeta.Par_Reader, count).Compile();
        }

19 View Source File : DbContextSync.cs
License : MIT License
Project Creator : 2881099

internal void ExecCommand() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, int> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], int>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(int));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(int)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Action funcDelete = () => {
				_affrows += dbContextBetch("DbContextBetchRemove");
				states.Clear();
			};
			Action funcInsert = () => {
				_affrows += dbContextBetch("DbContextBetchAdd");
				states.Clear();
			};
			Action<bool> funcUpdate = isLiveUpdate => {
				var affrows = 0;
				if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
				else affrows = dbContextBetch("DbContextBetchUpdate");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : DataContext.cs
License : MIT License
Project Creator : Accelerider

public void Import<T>(Expression<Func<T>> propertyExpression, string key = null)
        {
            var parameter = Expression.Parameter(typeof(T));
            var setter = Expression.Lambda<Action<T>>(
                Expression.replacedign(
                    propertyExpression.Body,
                    parameter),
                parameter).Compile();

            key = key ?? PropertySupport.ExtractPropertyName(propertyExpression);
            if (!_importPropertySetterDictionary.ContainsKey(key))
            {
                _importPropertySetterDictionary.Add(key, new List<Delegate>());
            }
            _importPropertySetterDictionary[key].Add(setter);
        }

19 View Source File : ExpressionExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static Expression<Func<T, bool>> AndAlso<T, TNav>(
            this Expression<Func<T, bool>> expr1,
            Expression<Func<TNav, bool>> expr2,
            Expression<Func<T, TNav>> navigationProperty
        )
        {
            var parameter = Expression.Parameter(typeof(T));
            var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
            var left = leftVisitor.Visit(expr1.Body);
            var navVisitor = new ReplaceExpressionVisitor(navigationProperty.Parameters[0], parameter);
            var nav = navVisitor.Visit(navigationProperty.Body); // Reset the navigation prop expression to start from the shared parameter
            var right = Expression.Invoke(expr2, nav); // Create an expression that navigates to the property

            return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left, right), parameter);
        }

See More Examples