How to filter in Dapper using a collection with multiple properties?

.net-core c# dapper

Question

I am a bit new to Dapper and am trying to find a clean way to pass a filter parameter to SQL Query for a collection with more than one property.

My collection looks like this:

[{
    Prop1: 'A Value 1',
    Prop2: 'B Value 1'
},
{
    Prop1: 'A Value 2',
    Prop2: 'B Value 2'
}]

Which should result in a SQL Query looking something like this:

select *
from SampleTable
where
([ColumnA]='A Value 1' and [ColumnB]='B Value 1')
or ([ColumnA]='A Value 2' and [ColumnB]='B Value 2')

Note: Something like whats shown below will not work because the two properties PropA and PropB need to filter together.

string query = @"select *
                from SampleTable
                where [ColumnA] in (@PropA_Value)
                and [ColumnB] in (@PropB_Value)"

con.Query<T>(query, new{PropA_Value = PropA,PropB_Value = PropB}).AsList();

Popular Answer

You can generate filter strings dynamically using the following helper class:

public static class DapperHelper
    {
        private const string SingleTupleFormat = " [{0}] = '{1}' {2}";
        private const string AndString = "AND";
        private const string OrString = "OR";

        private static string ToSqlTuple(List<Dictionary<string, string>> filters) 
        {
             string filterParam = string.Empty;
             foreach (var filter in filters)
             {
                 //Construct single tuple
                 string tuple = filter.ToList().Aggregate(string.Empty,
                 (current, pair) => current + String.Format(SingleTupleFormat, pair.Key, pair.Value, AndString));

                 //Concatenate tuples by OR, string.Format to combine the different filters
                 filterParam += string.Format(" ({0}) {1}", tuple.TrimEnd(AndString), OrString);
             }
             return filterParam.TrimEnd(OrString);
         }

        public static string TrimEnd(this string source, string value)
        {
            if (!source.EndsWith(value))
                return source;

            return source.Remove(source.LastIndexOf(value));
        }
    }

Usage:

string query = @"select *
                from SampleTable
                where @where";

List<Dictionary<string, string>> filters = new List<Dictionary<string, string>>() {
                new Dictionary<string, string>(){{"ColumnA", "A Value 1"},{"ColumnB", "A Value 2"}},
                new Dictionary<string, string>(){{"ColumnA", "B Value 1"},{"ColumnB", "B Value 2"}}
            };

var tuple = DapperHelper.ToSqlTuple(filters);
query = query.Replace("@where", string.IsNullOrEmpty(tuple) ? "1=1" : tuple); //Use 1=1 if tuple is empty or null

var data = con.Query<T>(query).AsList();

Query string looks like:

select *
from SampleTable
where  ( [ColumnA] = 'A Value 1' AND [ColumnB] = 'A Value 2' ) 
    OR ( [ColumnA] = 'B Value 1' AND [ColumnB] = 'B Value 2' )


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why