Dynamic linq query with multiple/unknown criteria

前端 未结 3 1020
醉酒成梦
醉酒成梦 2020-12-01 22:26

I am looking to implement a system whereby a use that \'build\' conditions and then return the resulting data back from the database. At present, there is a stored procedure

相关标签:
3条回答
  • 2020-12-01 22:35

    I think Dynamic LINQ will be one of option. DLINQ allows you to specify part of the LINQ query as "string" and DLINQ then compiles that string to Expression tree so that be passed to the underlying LINQ provider. Your need is also same i.e you need to create Expression trees at runtime.

    I would suggest you to make the property Operator in FieldCriteria as an Enum which represent all the required operations (equals, less then etc). Then you will need to write a function that takes a list of FieldCriteria and return a "expression" string which then can be fed into DLINQ to get the expression tree.

    0 讨论(0)
  • 2020-12-01 22:38

    The trick with LINQ would be to build an Expression from the data. As an example, to illustrate the example shown:

    var param = Expression.Parameter(typeof(MyObject), "t");
    
    var body = Expression.Or(
                Expression.Equal(Expression.PropertyOrField(param, "Email"), Expression.Constant("email@domain.com")),
                Expression.Call(Expression.PropertyOrField(param, "Email"), "Contains", null, Expression.Constant("mydomain"))
            );
    
    body = Expression.AndAlso(body, Expression.Equal(Expression.PropertyOrField(param, "Field1"), Expression.Constant("valuewewant")));
    body = Expression.AndAlso(body, Expression.NotEqual(Expression.PropertyOrField(param, "Field2"), Expression.Constant("valuewedontwant")));
    
    var lambda = Expression.Lambda<Func<MyObject, bool>>(body, param);
    
    var data = source.Where(lambda);
    

    In particular, note how AndAlso can be used to compose the various operations (the same as multiple Where, but simpler).

    0 讨论(0)
  • 2020-12-01 22:48

    This can be simply done by Linq where you attach additional operators to the query object. Here is an example.

    query = db.Contacts.Where( ... );
     query = query.Where( ... );
     query = query.Where( ... );
    

    This is a more simpler and short solution.

    0 讨论(0)
提交回复
热议问题