简体   繁体   中英

How should I pass an array to the FIELD statement using Dapper, c#

I am trying to pass an array as a parameter using Dapper. My array of values must go into the FIELD section.

I tried to join the array elements into a String and pass it. Still doesn't work.

Guid[] myArr = Ids.ToArray(); // Ids are List<Guid>
var script = @"SELECT * FROM table WHERE Id in @Ids ORDER BY FIELD(Id, @param)";
using (var connection = database.Connection)
            {
                return connection.Query<MyDataType>(script, new {Ids = Ids, param = myArr}).ToList();
            }

This query is just doing an Order By Id. I also passed in param = Ids. Still doesn't work.

According to this question SELECT * FROM X WHERE id IN (...) with Dapper ORM you should be able to do a WHERE in with dapper but the limit of the number of items in the array is something to watch out for.

Then you could also break out the ORDER BY FIELD SQL and use linq to do an OrderBy on your results.

Edit: Would this work?

Guid[] myArr = Ids.ToArray(); // Ids are List<Guid>
var script = @"SELECT * FROM table WHERE Id in @Ids)";
using (var connection = database.Connection)
{
    var myDataTypeObjects = connection.Query<MyDataType>(script, new {Ids = Ids}).ToList();
    myDataTypeObjects = myDataTypeObjects.OrderBy(x => Ids.IndexOf(x.Id)).ToList();
    return myDataTypeObjects;
}

Convert the list into array in parameter list of dapper.

 var sqlQuery = "Select * from table Where Columnname IN @periodIdStr";
 var result = dapperUOW.Connection.Query<Entity>(sqlQuery ,
                        param: new { periodIdStr = periodIds.ToArray() }, transaction: dapperUOW.Transaction).ToList();
        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM