I have a web app where users can get records from the database based on certain filtering criteria. They can get all records, or all records between two dates, or all records of a particular entity type, or all records for a particular user etc.. I'm using EF6 and just standard DbContext classes to query the DB
What I'm trying to do is build a query dynamically based on the request object and what properties aren't null. So if a user selects a from and to date, but no other criteria, the query should go off to the db and get all records between said dates. if the user doesn't select dates but an entity type, then the query should just filter on that property of the request object.
So in pseudo code, how would i do this when building the query
- Check all request object properties
- Which ever properties aren't null, add them to the query expression as a parameter
Here's my request object
public class ChangeLogRequestDto
{
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public string UserName { get; set; }
public string CallCenter { get; set; }
public string EntityType { get; set; }
public string PropertyName { get; set; }
public string CompanyId { get; set; }
}
And here's my Service method to take in this request object and build the query to get the records
public IEnumerable<ChangeLog> GetChangeLogWithFilter(ChangeLogRequest request)
{
// check the request object and build a query based on its values.
return dbContext.ChangeLogs.Where(query)
}
I've looked up other examples but given I'm unfamiliar with Expressions and Linq they're not making sense to me. Any ideas?