Ejemplo n.º 1
0
        public static MemberInitExpression InitType <TEntity>(IEnumerable <SelectColumn> columns, Expression node, AutoQueryableProfile profile)
        {
            var expressions = new Dictionary <string, Expression>();

            foreach (SelectColumn subColumn in columns)
            {
                Expression ex = GetMemberExpression <TEntity>(node, subColumn, profile);
                expressions.Add(subColumn.Name, ex);
            }

            Type type = null;

            if (profile.UseBaseType)
            {
                type = node.Type;
            }
            else
            {
                var properties = GetTypeProperties(expressions);
                type = RuntimeTypeBuilder.GetRuntimeType(node.Type, properties);
            }
            NewExpression ctor = Expression.New(type);

            return(Expression.MemberInit(ctor, expressions.Select(p => Expression.Bind(type.GetProperty(p.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance), p.Value))));
        }
Ejemplo n.º 2
0
        public static Expression <Func <TEntity, object> > GetSelector <TEntity>(string columns)
        {
            Dictionary <string, Expression> memberExpressions = new Dictionary <string, Expression>();

            ParameterExpression parameter = Expression.Parameter(typeof(TEntity), "p");
            var properties = new Dictionary <string, object>();

            foreach (string column in columns.Split(','))
            {
                var cols = column.Split('.');
                var ex   = GetMemberExpression(parameter, cols, 0);
                if (ex == null)
                {
                    continue;
                }
                string propName = column.Replace(".", "");
                memberExpressions.Add(propName, ex);
                if (ex is MemberExpression)
                {
                    properties.Add(propName, (ex as MemberExpression).Member as PropertyInfo);
                }
                if (ex is MethodCallExpression)
                {
                    var callExpression = (ex as MethodCallExpression);
                    properties.Add(propName, ex.Type);
                }
            }

            var dynamicType = RuntimeTypeBuilder.GetRuntimeType <TEntity>(properties);

            var ctor = Expression.New(dynamicType);

            var memberAssignments = dynamicType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                    .Select(p =>
            {
                return(Expression.Bind(p, memberExpressions.Single(me => me.Key == p.Name).Value));
            });

            var memberInit = Expression.MemberInit(ctor, memberAssignments);

            return(Expression.Lambda <Func <TEntity, object> >(memberInit, parameter));
        }