您好我想构建一个包含对象所有属性的动态Entity Framework Linq查询。实施例
我想: - 1)对象测试有5个公共属性。 2)我想循环遍历此对象并检查每个字符串属性是null还是空。 3)如果没有,我想编写一个查询,该查询将附加where条件以使用该属性值搜索实体。
public void CheckMyEntity(IQueryable<ABCEty> _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.<<I cant insert the property here>> == prop.GetValue(_MyEntityProperty,null));
}
}
}
任何帮助都非常有用!谢谢!
答案 0 :(得分:3)
您可以将每个PropertyInfo转换为lambda表达式并将其传递给查询
public static void CheckMyEntity(IQueryable<ABCEty> _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<MyEntity, bool> 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<Func<MyEntity, bool>>(equalityCheck, instance).Compile();
}
答案 1 :(得分:0)
有一个小型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一样处理它。