3

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.

4
  • 3
    Interesting; short version is "that's the first time I've ever seen that syntax, and consequently Dapper currently has no support for that" - so: nothing great right now. Commented May 9, 2019 at 20:02
  • When I join my values to a String, I get "'1','2','3'". I wanted to get rid of the double quotes at the start and end; so I used .Trim('"'). Could not make it work Commented May 9, 2019 at 20:06
  • You sure those double quotes isn't just the debugger being "helpful"? It tries to format text into legal C# syntax, which means it adds quotes, and escapes problematic characters, both of which there are ample amounts of questions about here on Stack Overflow. Commented May 9, 2019 at 20:50
  • Years later... from my understanding dapper does not support arrays in the order by. Commented Aug 29, 2023 at 20:46

2 Answers 2

1

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();
        
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

1 Comment

No, I cannot use OrderBy using Linq. It defeats the whole purpose of using FIELD()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.