IQueryable中的Linq表达式过滤器

时间:2019-03-22 09:40:33

标签: c# linq lambda expression

我想在IQueryable中创建通用表达式过滤

public class Vehicle
    {
        public int Id { get; set; }
        public string VehicleNO { get; set; }
        public int DriverId { get; set; }
        public Driver Driver {get;set;}
    }

    public class Driver
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
  

operator =“包含”,字段名称=“ Driver.Name”,值过滤器=   “米歇尔”

我不知道如何过滤驱动程序名称。 这是我的完整代码

IQueryable<SysClientSiteUser> query = entity.SysClientSiteUsers.Include(i => i.SysClientSiteRole);

Dictionary<string, string> dtFilter = new Dictionary<string, string>();
dtFilter.Add("VehicleNo", "A123");


Dictionary<Type, Func<string, object>> lookup = new Dictionary<Type, Func<string, object>>();


lookup.Add(typeof(string), x => { return x; });
lookup.Add(typeof(long), x => { return long.Parse(x); });
lookup.Add(typeof(int), x => { return int.Parse(x); });
lookup.Add(typeof(double), x => { return double.Parse(x); });

var paramExpr = Expression.Parameter(typeof(Vehicle), "VehicleNo");

var keyPropExpr = Expression.Property(paramExpr, "VehicleNo");

if (!lookup.ContainsKey(keyPropExpr.Type))
    throw new Exception("Unknown type : " + keyPropExpr.Type.ToString());

var typeDelegate = lookup[keyPropExpr.Type];
var constantExp = typeDelegate("A123");
var eqExpr = Expression.Equal(keyPropExpr, Expression.Constant(constantExp));
var condExpr = Expression.Lambda<Func<SysClientSiteUser, bool>>(eqExpr, paramExpr);
query = query.Where(condExpr);

对于普通字段,它正在工作。但是如果我想给驱动程序命名。这是行不通的。如何调用“ Driver.Name”?

1 个答案:

答案 0 :(得分:0)

您可以使用辅助函数将嵌套的属性名称字符串转换为访问给定Expression的属性的ParameterExpression并键入:

private static Expression MakePropertyExpression<T>(string propertyName, Expression baseExpr) =>
    propertyName.Split('.').Aggregate(baseExpr, (b, pname) => Expression.Property(b, pname));