Constructing Dynamic LINQ queries with all propert

2019-06-12 03:05发布

问题:

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

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!

回答1:

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


回答2:

There is a small Dynamic Linq library that does textual evaluation. http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx

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

Simply put this class does evaluation of the text and converts it into a Linq expression tree that most LinQ providers like Entity Framework can process.