使用对象的所有属性构造动态LINQ查询

嗨,我想构建一个动态的Entity Framework Linq查询与对象的所有属性。 例

我想: – 1)对象测试有5个公共属性。 2)我想遍历此对象并检查每个字符串属性是null还是空。 3)如果没有,我想编写一个查询,该查询将附加where条件以使用该属性值搜索实体。

public void CheckMyEntity(IQueryable _allABCs, MyEntity _MyEntityProperty) { foreach (var prop in _MyEntityProperty.GetType().GetProperties()) { if (!String.IsNullOrEmpty(prop.GetValue(_MyEntityProperty,null).ToString())) { _allABCs = _allABCs.Where(temp => (temp.ABCMyEntitys.All(MyEntity => MyEntity.MyEntity.<> == prop.GetValue(_MyEntityProperty,null)); } } } 

任何帮助都会非常有用! 谢谢!

您可以将每个PropertyInfo转换为lambda表达式并将其传递给查询

 public static void CheckMyEntity(IQueryable _allABCs, MyEntity _myEntity) { foreach (var propertyInfo in _myEntity.GetType().GetProperties()) { if (!String.IsNullOrEmpty(propertyInfo.GetValue(_myEntity, null).ToString())) { //access to modified closure PropertyInfo info = propertyInfo; _allABCs = _allABCs.Where(temp => temp.ABCMyEntitys.All(GenerateLambda(_myEntity, info))); } } var result = _allABCs.ToList(); } private static Func GenerateLambda(MyEntity _myEntity, PropertyInfo propertyInfo) { var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); var property = Expression.Property(instance, propertyInfo); var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null)); var equalityCheck = Expression.Equal(property, propertyValue); return Expression.Lambda>(equalityCheck, instance).Compile(); } 

有一个小型Dynamic Linq库可以进行文本评估。 http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx

 Dim query = Northwind.Products .Where("CategoryID=2 And p.UnitPrice>3") .OrderBy("SupplierID") 

简单地说,这个类对文本进行评估并将其转换为Linq表达式树,大多数LinQ提供者都可以像Entity Framework一样处理它。