Filtering with Expression> using view model

c# entity-framework-core filtering

Question

I have a method for paginating a table in a database. Paginating part is not important, so the only focus is filtering part.

Since Where method from Entity Framework Core asks for Expression<Func<T>> as a parameter, where T is an actual model and I have action in controller which asks for a valid view model, how can I use that view model to generate Expression<Func<T>> from that view model?

I want to be able to filter table based on filled parameters in the view model.

1
0
1/18/2020 2:15:43 PM

Popular Answer

Well you basically need the Expression<Func<YourModel, bool>>. You build a filter to pass to EF. The below info is more than enough to get you started.

So imagine you have a class like the below. This can be any class not just a ViewModel.

public class Person
{
 public int Id {get;set;}
 public string Name {get;set;}
}

The expression would look sth like this.

Expression<Func<Person,bool>> predicate = p => p.Name == "Some name";
db.People.Where(predicate); // How you would use it in a db context

You can also view this link that uses LinqKit.You do not have to use LinqKit but has some nice examples http://www.albahari.com/nutshell/linqkit.aspx

I want to be able to filter table based on filled parameters in the view model.

Since you want the above you can append to your predicate and just pass it to your Where,Any,Count... as one. You can see a lot of techniques to how to append to your filter here: How to Append to an expression

My favorite way of appending is using linqkit predicate builder http://www.albahari.com/nutshell/predicatebuilder.aspx In the above link many techniques are showcased including the predicate builder.

0
1/18/2020 7:50:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow