Skip to content
Advertisement

Creating Dynamic LINQ Queries using Expression Trees

I am having trouble being able to replicate multiple .Wheres in my linq query using Expression Trees, I need this query to be dynamic since its a search feature.The database I will be querying eventually will get large so i need to be efficient and cant filter client side. I am at least trying to start by filtering by 3 of these columns. Below I added three of the ids im trying to filter by. I have read alot into expression trees but could use someones help to actually apply them to what im doing because they are confusing me.

    public int? heightId { get; set; }
    public int? ageId { get; set; }
    public int? genderId { get; set; }

Advertisement

Answer

It is not dynamic, because you know the columns in advance. You don’t need to use expression trees as well. You can just apply the filters conditionally:

public Class[] FindByFilter(int limit, int? heightId = null, int? ageId = null, int? genderId = null)
{
    var classes = databaseContext.Set<Class>();

    if (heightId.HasValue)
        classes = classes.Where(c => c.HeightId == heightId.Value);

    if (ageId.HasValue)
        classes = classes.Where(c => c.AgeId == ageId.Value);

    if (heightId.HasValue)
        classes = classes.Where(c => c.GenderId == genderId.Value);    

    return classes.Take(limit).ToArray();
}

So, now FindByFilter(10, 1, null, 2) or equivalent FindByFilter(10, heightId: 1, genderId: 2) will return TOP 10 rows with height 1, gender 2, but any age.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement