I have a class that contains a number of properties of type bool.
public class FilterModel
{
public bool Hotel { get; set; }
public bool Apartment { get; set; }
public bool Guesthouse { get; set; }
}
I am constructing a LINQ query dynamically based on whether or not these properties are true or false. For example if I had an instance of this class and Hotel was set to true. I want to generate a LINQ query something like
var q = from accom in db.Accommodation
where accom.Hotel == true
select accom;
Thanks in advance
Are you looking for something like this?
IQueryable<Accommodation> query = db.Accommodation;
if (filterModel.Hotel) query = query.Where(a => a.Hotel);
if (filterModel.Apartment) query = query.Where(a => a.Apartment);
if (filterModel.Guesthouse) query = query.Where(a => a.Guesthouse);
return query;
You want something like this:
var filterModel = GetFilterModelFromSomewhere();
var q = db.Accomodation;
if (filterModel.Hotel)
q = q.Where(accom => accom.Hotel);
if (filterModel.Apartment)
q = q.Where(accom => accom.Apartment);
if (filterModel.Guesthouse)
q = q.Where(accom => accom.Guesthouse);
Since the query isn't executed until you enumerate it (via ToList() or an equivalent function) you can build it piecemeal in code based on dynamic conditions.
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