Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine multiple INSERT INTO's with prepared statements?

Using Dapper, is there a way to form this into one query with the prepared statements?
The length of userIds is dynamic.

        public static void LinkUsersToChatroom(int chatroomId, int[] userIds)
        {
            using SqlConnection connection = new(connectionString);

            connection.Execute(
            "INSERT INTO chatroom_users (chatroomId, userId) VALUES (@chatroomId, @userId)",
                new { chatroomId, userId = userIds[0] });

            connection.Execute(
            "INSERT INTO chatroom_users (chatroomId, userId) VALUES (@chatroomId, @userId)",
                new { chatroomId, userId = userIds[1] });

            connection.Execute(
            "INSERT INTO chatroom_users (chatroomId, userId) VALUES (@chatroomId, @userId)",
                new { chatroomId, userId = userIds[2] });
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One of the many advantages of Dapper over straight ADO.NET is the simplicity of inserting a list of the same data to your table.
You just need a list of a class where the properties of the class have the same name of your database fields, so…

private class ChatRoomUser
{
    public int chatroomId {get;set;}
    public int userId {get;set;}
}

public static void LinkUsersToChatroom(int chatroomId, int[] userIds)
{
    var users = userIds.Select(x => new ChatRoomUser
    { 
        chatroomId = chatroomId, 
        userIds = x
    };
    using SqlConnection connection = new(connectionString);
    connection.Execute("INSERT INTO chatroom_users (chatroomId, userId) VALUES (@chatroomId, @userId)", 
                        users);

}

This approach if you want to maintain the actual interface of your current method, but of course, nothing prevents you to build the list directly where you build the array and pass the list instead of the two parameters or create an overload of this method that accepts the list as its input.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading