Creating dynamic Linq query based on property values
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 == tr开发者_StackOverflow中文版ue
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.
精彩评论