Procedurally create a dynamic object for Dapper

I saw a lot of posts about creating ExpandoObject objects, etc., but in my case this does not work. I need to create an object like

 var someObj = new { term1 = "someValue", term2 = "other", ... }; 

Basically, we use Dapper , and we need to dynamically create a query where the WHERE is created from the given array of arguments. We are not generalizing requests! This is the only method that receives a variable number of arguments, and we need to check the OR each value in one column.

Currently, the only viable solution is to return and directly use System.Data.SqlClient.SqlConnection , or is there a way to make this work?

Update:

This is what most likely should work, but does not:

 string inWhere = null; dynamic inTerms = new ExpandoObject(); IDictionary<string, object> inTermsDict = inTerms; if (!(string.IsNullOrEmpty(filter.Term) || string.IsNullOrWhiteSpace(filter.Term))) { inWhere = "(" + string.Join(" OR ", filter.Terms.Select((t, i) => "{0} LIKE @p" + i)) + ")"; int termIndex = 0; foreach (string term in filter.Terms) { inTermsDict.Add("p" + (termIndex++), term); } } // ... var rows = db.Query("SELECT * FROM {table} WHERE {baseCondition}" + (string.IsNullOrEmpty(inWhere) ? "" : string.Format(" AND " + inWhere, "columnName")), inTerms as object); 
+4
source share
1 answer

Just to answer my own question, as we found the right solution earlier today.

Simply put, we found IDynamicParameters And this class just solves everything, acting like a Dictionary .

 var inTerms = new Dapper.DynamicParameters(); inTerms.Add("@p" + (termIndex++), somveValue); 

Everyone is happy!

+6
source

All Articles