获取属性名: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));