Creating a 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 building a LINQ query dynamically based on whether these properties are true or false. For example, if I had an instance of this class and the hotel was set to the truth. I want to generate LINQ query something like

var q = from accom in db.Accommodation
                     where accom.Hotel == true 
                     select accom;

Thanks in advance

+3
source share
2 answers

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;
+3
source

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 request is not executed until you list it (through ToList () or an equivalent function), you can build it in parts in the code based on dynamic conditions.

+2
source

Source: https://habr.com/ru/post/1778174/


All Articles