简体   繁体   English

使用 Dapper 将数组传递给 SQL 参数

[英]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.我想在表中插入一个值数组(如果它们不存在),该数组很小并且不会超过 10 项,因此传入插入是安全的。

How can I execute this code with Dapper?如何使用 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 SO上有一个类似的问题,但它是针对IN子句的: dapper“IN”子句不使用多个值

Is there another way in Dapper to pass an array in my case?在我的情况下,Dapper 还有另一种传递数组的方法吗?

What you are trying to do isn't possible.你试图做的事情是不可能的。 But instead of the array, you can just use your countries collection.但是,您可以只使用您的countries地区集合,而不是数组。 It has a Name property and Dapper will run the query for each item in a suitable collection:它有一个 Name 属性,Dapper 将为合适集合中的每个项目运行查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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