简体   繁体   中英

Passing an array to SQL parameter with Dapper

I want to insert into a table an array of values if they don't exist, the array is small and would not exceed 10 items, so it is safe to pass in an insert.

How can I execute this code with Dapper? I tried the following but I am getting an error:

const string sqlSymbolsInsert = 
    @"INSERT INTO Country (Name)
        SELECT NewNames.Name FROM (VALUES(@Names)) AS NewNames (Name)
        WHERE NOT EXISTS (SELECT 1 FROM Country AS C WHERE C.Name = NewNames.Name);";

await using var cn = new SqlConnection(CONNECTION_STRING);
await cn.ExecuteAsync(sqlSymbolsInsert, new { Names = countries.Select(x => x.Name) });

The error is:

Core Microsoft SqlClient Data Provider: Incorrect syntax near ','.

There is a similar problem on SO, but it is for the IN clause: dapper "IN" clause not working with multiple values

Is there another way in Dapper to pass an array in my case?

What you are trying to do isn't possible. But instead of the array, you can just use your countries collection. It has a Name property and Dapper will run the query for each item in a suitable collection:

const string sqlSymbolsInsert = 
    @"INSERT INTO Country (Name)
        SELECT @Name WHERE NOT EXISTS 
        (
            SELECT  1
            FROM    Country 
            WHERE   Name = @Name 
        )";

await using var cn = new SqlConnection(CONNECTION_STRING);
await cn.ExecuteAsync(sqlSymbolsInsert, countries);

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