Let's say I have Customers table and I want to filter it by the following:
if I had to build an SQL string for this filter, it would be something like this:
if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;
So, basically, the user can filter by some, but not necessary all fields.
How do you do this using Entity Framework ?
Thanks !
Global query filters are LINQ query predicates applied to Entity Types in the metadata model (usually in OnModelCreating). A query predicate is a boolean expression typically passed to the LINQ Where query operator. EF Core applies such filters automatically to any LINQ queries involving those Entity Types.
EF Core applies such filters automatically to any LINQ queries involving those Entity Types. EF Core also applies them to Entity Types, referenced indirectly through use of Include or navigation property. Some common applications of this feature are: Soft delete - An Entity Type defines an IsDeleted property.
Note the use of a DbContext instance level field: _tenantId used to set the current tenant. Model-level filters will use the value from the correct context instance (that is, the instance that is executing the query). It is currently not possible to define multiple query filters on the same entity - only the last one will be applied.
EF Core applies such filters automatically to any LINQ queries involving those Entity Types. EF Core also applies them to Entity Types, referenced indirectly through use of Include or navigation property.
LINQ to Entity queries return IQueryable
's, so you can build your query this way:
IQueryable<Person> query = context.People;
if (Country != "All")
{
query = query.Where(p => p.Country == Country);
}
if (Income != "All")
{
query = query.Where(p => p.Income == Income);
}
if (Age != "All")
{
query = query.Where(p => p.Age == Age);
}
List<Person> fetchedPeople = query.ToList();
This case is almost too simple, but this is very helpful in more complex situations when you need to add filtering dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With