How can I create a custom generic linq filter that will check if the generic class contains a property name and returns the query…
I have something like:
public static IQueryable<T> GetAllByType<T>(
this IQueryable<T> customQuery, string seller) where T : class, new()
{
customQuery = customQuery.Where(i => i.GetType().Name == "TypeOfSeller");
return customQuery;
}
If the property type on the table T exists then I want to filter the expression using the string seller passed in as a parameter…
simply: return an expression which will filter this table by the seller param which could be “big”, “small” etc.
I would refactor it a bit so that there’s no “if” involved but that I’m only sending the entities that qualify to the method.
The next thing you want to consider is that if there are multiple entity models that share a property name and you want to share logic regarding that property name, utilize the
partialaspect of the code-generated classes to extend those classes and have each of them implement an interface.This will allow you to add the interface to the list of constraints on the method and also allow you to simply utilize the
TypeOfSellerproperty directly without trying to resort to other methods (such as reflection).