Ejemplo n.º 1
0
    internal static Expression <Func <T, object> > GetOrderExpression <T>(ParsedOrdering order, IGridifyMapper <T> mapper)
    {
        var exp = mapper.GetExpression(order.MemberName);

        switch (order.OrderingType)
        {
        case OrderingType.Normal:
            return(exp);

        case OrderingType.NullCheck:
        case OrderingType.NotNullCheck:
        default:
        {
            // member should be nullable
            if (exp.Body is not UnaryExpression unary || Nullable.GetUnderlyingType(unary.Operand.Type) == null)
            {
                throw new GridifyOrderingException($"'{order.MemberName}' is not nullable type");
            }

            var prop     = Expression.Property(exp.Parameters[0], order.MemberName);
            var hasValue = Expression.PropertyOrField(prop, "HasValue");

            switch (order.OrderingType)
            {
            case OrderingType.NullCheck:
            {
                var boxedExpression = Expression.Convert(hasValue, typeof(object));
                return(Expression.Lambda <Func <T, object> >(boxedExpression, exp.Parameters));
            }

            case OrderingType.NotNullCheck:
            {
                var notHasValue     = Expression.Not(hasValue);
                var boxedExpression = Expression.Convert(notHasValue, typeof(object));
                return(Expression.Lambda <Func <T, object> >(boxedExpression, exp.Parameters));
            }

            // should never reach here
            case OrderingType.Normal:
                return(exp);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        }
    }
Ejemplo n.º 2
0
    public static IEnumerable <Expression <Func <T, object> > > GetOrderingExpressions <T>(this IGridifyOrdering gridifyOrdering,
                                                                                           IGridifyMapper <T>?mapper = null)
    {
        if (string.IsNullOrWhiteSpace(gridifyOrdering.OrderBy))
        {
            throw new GridifyQueryException("OrderBy is not defined or not Found");
        }


        var members = ParseOrderings(gridifyOrdering.OrderBy !).Select(q => q.MemberName).ToList();

        if (mapper is null)
        {
            foreach (var member in members)
            {
                Expression <Func <T, object> >?exp = null;
                try
                {
                    exp = GridifyMapper <T> .CreateExpression(member);
                }
                catch (Exception)
                {
                    // skip if there is no mappings available
                }

                if (exp != null)
                {
                    yield return(exp);
                }
            }
        }
        else
        {
            foreach (var member in members.Where(mapper.HasMap))
            {
                yield return(mapper.GetExpression(member) !);
            }
        }
    }