Skip to content
Advertisement

Dapper query with dynamic list of filters

I have a c# mvc app using Dapper. There is a list table page which has several optional filters (as well as paging). A user can select (or not) any of several (about 8 right now but could grow) filters, each with a drop down for a from value and to value. So, for example, a user could select category “price” and filter from value “$100” to value “$200”. However, I don’t know how many categories the user is filtering on before hand and not all of the filter categories are the same type (some int, some decimal/double, some DateTime, though they all come in as string on FilterRange).

I’m trying to build a (relatively) simple yet sustainable Dapper query for this. So far I have this:

I Keep getting an error saying “… filterRanges cannot be used as a parameter value”

Is it possible to even do this in Dapper? All of the IEnumerable examples I see are where in _ which doesn’t fit this situation. Any help is appreciated.

Advertisement

Answer

I was able to find a solution for this. The key was to convert the List to a Dictionary. I created a private method:

Then to build my query,

Special note: Be very careful here as the column name is not a parameter and you could open your self up to injection attacks (as @Popa noted in his answer). In my case those values come from an enum class and not from user in put so I am safe.

The rest is pretty straight forwared:

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