I am trying to use the SearchExtensions library to simplify writing IQueryable searching code but I would like to provide the properties to search on as strings and not an Expression

https://github.com/ninjanye/SearchExtensions

Essentially the library lets you do this:

var result = queryableData.Search(x => x.Property1) .Containing("searchTerm"); 

But I need to do this:

var result = queryableData.Search("Property1") .Containing("searchTerm"); 

Because of two reasons:

  • This is a Web API and the JSON request that comes in will have the column name they want to search, and the search value.
  • The service handling the request is generic so I do not know the properties of the type at compile time, but I do have the JSON.columns[i].name which is the property name of type T.

Possible alternatives that I am not a fan of

  • Extract the Expression<Func<T, string>>[] propertiesToSearch and expose it as a params property to the caller (in this case the controller action). This way the developer has to explicitly rattle off the columns that are allowed to be searched, which is fine but its a lot of extra boilerplate depending on your needs (if you want to enable searching dates AND strings you have to expose two propertiesToSearch because SearchExtensions only has overloads for one or the other)
  • Expose the queryable to the caller, maybe through a Func and let the controller action build out the search through a series of conditions around JSON.columns[i].name and MyViewModel properties.

I think my issue boils down to my lack of experience with reflection and expressions, expression trees, expression visitors etc.

The magic is here: https://github.com/ninjanye/SearchExtensions/blob/master/NinjaNye.SearchExtensions/Helpers/ExpressionBuilders/ContainsExpressionBuilder/QueryableContainsExpressionBuilder.cs

Full code (line 60)

https://www.irccloud.com/pastebin/XhDlFzqH/irc%20help.cs

submitted by /u/Lord_Zero
[link] [comments]

Leave a Reply