Domanda

Does Dapper use numbered parameters such as in Massive(@0, @1, ...) unlike named (@a, @b, ...)?

It is necessary to create a query as

//select @0 as val union select @1 union select @2 union select @3 union select @4 
//union select @5 union select @6 union select @7 union select @8 union select @9
var sb = new StringBuilder("select @0 as val");
for (int i = 1; i < 10; i++)
{
    sb.AppendFormat(" union select @{0}", i);
}
var query = sb.ToString();
//---Dapper = fail
var db = Connection;
var list = db.Query(query, param: new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
//---Massive = ok
var db2 = new Massive.DynamicModel(coins);
var list2 = db2.Query(query, args: new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

What are the solutions to the problem for Dapper?

È stato utile?

Soluzione

Massive uses positional arguments in their queries but dapper uses named ones. So in massive you can pass in parameter arrays like: new int[] {1,2,3} while in dapper you need to pass in parameter objects like new { a = 1, b = 2 }.

To achieve a similar solution with dapper you can create a DynamicParameters object where you can pass your parameters dictionary where the key is the name of the parameter and value is the value of parameter, something like {"0",0}, {"1", 1}, etc

You can easily turn an array to a dictionary with LINQ:

var dictionary = new object[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    .Select((item, ind) => new {ind = ind.ToString(), item})
    .ToDictionary(item => item.ind, item => item.item);

DynamicParameters p = new DynamicParameters(dictionary);

var list = db.Query(query, param: p);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top