构建动态LINQ查询与对象的所有属性 [英] Constructing Dynamic LINQ queries with all properties of an object

查看:211
本文介绍了构建动态LINQ查询与对象的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想建立一个动态的实体框架LINQ查询与对象的所有属性。示例

Hi I want to construct a dynamic Entity Framework Linq query with all the properties of an object. Example

我想: - 1)对象测试有5个公共属性。 2)我想通过这个对象的循环,并检查是否每个字符串属性为null或空。 3)如果没有,我想写这将追加WHERE条件来搜索实体的属性的值的查询。

I want to :- 1) Object test has 5 public properties. 2) I want to loop through this object and check if each string property is null or empty. 3) If not, I want to write a query that will append a where condition to search the Entity with this value of the property.

    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));
            }
        }
    }

任何帮助将是非常有用的!谢谢!

Any help would be very useful! Thanks!

推荐答案

您可以将每个的PropertyInfo为lambda EX pression并将其传递到查询

You can turn each PropertyInfo into a lambda expression and pass that into the query

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();
}

这篇关于构建动态LINQ查询与对象的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆