IN Query

  • Dapper natively supports IN() queries, no manual comma‑separated string concatenation required.
  • Rule: Pass an array / List collection as the parameter, Dapper will automatically expand it to generate the IN condition.
  • Fixed SQL syntax: WHERE Id IN @ids, do not add extra parentheses. Wrong syntax: IN (@ids).
  • Benefits: Fully parameterized queries, eliminates SQL injection risks.

Example

using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;
using System.Collections.Generic;

static void Main(string[] args)
{
    var connStr = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;
    using (IDbConnection db = new MySqlConnection(connStr))
    {
        string sql = "SELECT * FROM student WHERE Id IN @ids";

        // Works with int[] arrays / List<int>
        int[] idArray = {3,4};
        List<Student> studentList = db.Query<Student>(
            sql,
            new { ids = idArray }
        ).ToList();
    }
}Code language: JavaScript (javascript)
Both parameter formats work
// Option 1: Array (original sample)
new { ids = new int[] {3,4} }

// Option 2: List collection (more common in real projects)
new { ids = new List<int> {3,4,5} }Code language: PHP (php)

Bulk Delete

string sqlDelete = "DELETE FROM student WHERE Id IN @ids";
int rows = db.Execute(sqlDelete, new { ids = new int[]{2,5} });Code language: JavaScript (javascript)

Multi‑condition IN Query

string sql = "SELECT * FROM student WHERE Id IN @ids AND Email IN @emails";
var param = new
{
    ids = new int[]{1,2},
    emails = new string[]{"a@gmail.com","b@gmail.com"}
};
var list = db.Query<Student>(sql, param).ToList();Code language: PHP (php)

IN Query

Leave a Reply

Your email address will not be published. Required fields are marked *