tmsmith / Dapper-Extensions

Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs. For more advanced querying scenarios, Dapper Extensions provides a predicate system. The goal of this library is to keep your POCOs pure by not requiring any attributes or base class inheritance.
1.79k stars 586 forks source link

Is it possible for dynamic filter using predicates #277

Closed matigarowel closed 2 years ago

matigarowel commented 2 years ago

Ex for dynamic filter: public async Task < IActionResult > SearchPerson(List searchModel) { using (SqlConnection cn = new SqlConnection(_connectionString)) { cn.Open(); var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List() }; foreach(s in searchModel){ pg.Predicates.Add(Predicates.Field(f => f[s.Field], s.Operator, s.Value)); } IEnumerable list = cn.GetList(pg); cn.Close(); } }

valfrid-ly commented 2 years ago

Didn't understand the question.

You just posted a code sample.

What's happening with it?

matigarowel commented 2 years ago

I would like to create PredicateGroup that will bind base on value of searchModel entity to Predicates.Field< Person >.

For Example:

var searchModel = [ { Field: 'Id', Value: 1, Operator: Operator.Eq }, { Field: 'Active', Value: true, Operator: Operator.Like }, { Field: 'LastName', Value: 'Br%', Operator: Operator.Like } ];

var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List() };

foreach(s in searchModel){ pg.Predicates.Add(Predicates.Field(f => "How do I set the searchModel.Field value here since it is function expressison for Person entity?", s.Operator, s.Value)); }

valfrid-ly commented 2 years ago

This should use your entity as it's the one who has the mapping.

You actually need something like this, without the expression:

public async Task < IActionResult > SearchPerson(List searchModel)
{
  using (SqlConnection cn = new SqlConnection(_connectionString))
  {
    cn.Open();
    var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List() };
    pg.Predicates.Add(Predicates.Field<Person>(f => f[s.Field], s.Operator, s.Value));

    foreach(s in searchModel){
    pg.Predicates.Add(Predicates.Field<Person>(f[s.Field], s.Operator, s.Value));
   }
   IEnumerable list = cn.GetList(pg);
   cn.Close();
   }
  }

The catch with this is that the name of the property has to match EXACTLY the name in the object.