I just mixed the answers. this code run a dynamic query and convert result to dictionary list.
public List < Dictionary < string,object >> DataTableToDictionaryList(DataTable table) {
List < Dictionary < string,
object >> parentRow = new List < Dictionary < string,
object >> ();
Dictionary < string,
object > childRow;
foreach(DataRow row in table.Rows) {
childRow = new Dictionary < string,
object > ();
foreach(DataColumn col in table.Columns) {
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return (parentRow);
}
List < Dictionary < string,object >> RunDynamicQuery(string sql, Dictionary < string, Object > parameters = null, int resultSet = 0, CommandType commandType = CommandType.Text) {
// creates resulting dataset
var resultDataSet = new DataSet();
// creates a data access context (DbContext descendant)
using(var context = new DataDbContext()) {
// creates a Command
var conn = context.Database.Connection;
var cmd = conn.CreateCommand();
cmd.CommandType = commandType;
cmd.CommandText = sql;
if (parameters != null) {
// adds all parameters
foreach(var pr in parameters) {
var p = cmd.CreateParameter();
p.ParameterName = pr.Key;
p.Value = pr.Value;
cmd.Parameters.Add(p);
}
}
try {
// executes
if (conn.State != ConnectionState.Open) {
conn.Open();
}
var reader = cmd.ExecuteReader();
// loop through all resultsets (considering that it's possible to have more than one)
int currentResultSet = -1;
do {
currentResultSet++;
//skip lower resultsets
if (resultSet > currentResultSet) {
continue;
}
// loads the DataTable (schema will be fetch automatically)
var tb = new DataTable();
tb.Load(reader);
resultDataSet.Tables.Add(tb);
//make sure to get only one result set
break;
} while (! reader . IsClosed );
}
finally {
// closes the connection
context.Database.Connection.Close();
}
}
return DataTableToDictionaryList(resultDataSet.Tables[0]);
}