获取属性名:PropertyNameHelper

获取属性名:PropertyNameHelper

 

namespace NCS.Infrastructure.Querying
{
    public static class PropertyNameHelper
    {
        public static string ResolvePropertyName<T>(Expression<Func<T, object>> expression)
        {
            var expr = expression.Body as MemberExpression;
            if (expr == null)
            {
                var u = expression.Body as UnaryExpression;
                expr = u.Operand as MemberExpression;
            }

            return expr.ToString().Substring(expr.ToString().IndexOf(".") + 1);
        }

        public static string ResolvePropertyName<T>(Expression<Func<T>> expression)
        {
            var expr = expression.Body as MemberExpression;
            if (expr == null)
            {
                var u = expression.Body as UnaryExpression;
                expr = u.Operand as MemberExpression;
            }

            return expr.ToString().Substring(expr.ToString().IndexOf(".") + 1);
        }
    }
}

使用:

        /// <summary>
        /// 创建Criterion对象,示例1:
        /// Criterion.Create<Product>(p=>p.Color.Id, id, CriteriaOperator.Equal);
        /// 
        /// 示例2:类对象中的另一个类对象的属性创建Criterion,
        /// 例如DataPoint的一个属性ModuleBelongTo的类型是Module,而Module有int类型的Id属性,
        /// 即类的结构如下:
        /// DataPoint datapoint = new DataPoint();
        /// datapoint.ModuleBelongTo = new Module();
        /// 
        /// 用datapoint.ModuleBelongTo.Id创建Criterion
        /// Criterion.Create<DataPoint>(p => p.ModuleBelongTo.Id, 2, CriteriaOperator.Equal)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="value"></param>
        /// <param name="criteriaOperator"></param>
        /// <returns></returns>
        public static Criterion Create<T>(Expression<Func<T, object>> expression, object value, CriteriaOperator criteriaOperator)
        {
            string propertyName = PropertyNameHelper.ResolvePropertyName<T>(expression);
            Criterion criterion = new Criterion(propertyName, value, criteriaOperator);

            return criterion;
        }

 

                query.AddCriterion(Criterion.Create<DataPointHistoryData>(p => p.DataPoint.Id, request.DataPointId, CriteriaOperator.Equal));

 

转载于:https://www.cnblogs.com/easy5weikai/p/3230134.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值