How to filter properties of derived classes in a DbContext with dynamic LINQ

45 Views Asked by At

i’m having some trouble trying to make a criteria filter for mi API, let me explain.

I have the class A, with some common properties, like: Id, Created_at, Deleted_at, etc…

And i also have the subclasses Subclass_B, Subclass_C, Subclass_D, and so on…

The thing is, each of those subclasses have their own properties, like: Name, Lastname, Country, etc…

I want to make a filter for those classes. I’m currently receiving a dictionary with a Key value representing the property and the desired prop value to search for, and it brings without trouble the Object saved in the Database that has that key and value, BUT it only works when you filter with a property that the father class, A, has.

Here’s a piece of code:

public async Task<List<A>> Filter(JObject criteria)
{
    var query = _context.A.AsQueryable();

    foreach (KeyValuePair<string, JToken> filter in criteria)
    {
        var filterExpression = $"{filter.Key} == ";

        query = query.Where(filterExpression, filter.Value.ToString());
    }

    return await query.ToListAsync();
}

criteria JSON:

{ "Id": "446" }

Then, when i send in the criteria a property that only the Subclass_B has, for example "Name" , it throws an exception:

System.Linq.Dynamic…… 'No property or field 'MyProperty' exists in type 'A''.

How can i make it so i can filter through all my derived classes too? Oh, and beforehand: I will not know the type of the Class i'll be filtering, i'll just have the criteria and i have to filter through all of the A's derived classes till anyone matches the given criteria

Thanks in advance!

0

There are 0 best solutions below