gpt4 book ai didi

c# - Dapper 和列表参数在 ',' 附近返回不正确的语法

转载 作者:行者123 更新时间:2023-12-05 09:36:22 26 4
gpt4 key购买 nike

我有以下使用 Dapper 的代码:

public async Task GetClientsInvoices(List<long> clients, List<int> invoices)
{
var parameters = new
{
ClientIds = clients,
InvoiceIds = invoices
};

string sqlQuery = "SELECT ClientId, InvoiceId, IsPaid" +
"FROM ClientInvoice " +
"WHERE ClientId IN ( @ClientIds ) " +
"AND InvoiceId IN ( @InvoiceIds )";

var dbResult = await dbConnection.QueryAsync<ClientInvoicesResult>(sqlQuery, parameters);
}

public class ClientInvoicesResult
{
public long ClientId { get; set; }

public int InvoiceId { get; set; }

public bool IsPaid { get; set; }
}

它基于 sql server profiler 产生这个

exec sp_executesql N'SELECT ClientId, InvoiceId, IsPaid FROM ClientInvoice WHERE ClientId IN ( (@ClientIds1) ) AND InvoiceId IN ( (@InvoiceIds1,@InvoiceIds2) )',N'@InvoiceIds1 int,@InvoiceIds2 int,@ClientIds1 bigint',InvoiceIds1=35,InvoiceIds2=34,ClientIds1=4

执行时出现以下错误

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.

我有两个问题:

  1. 我做错了什么,我得到了这个异常?

  2. 为什么 dapper 翻译这个查询并使用 sp_executesql 执行它。我如何强制它使用像

    这样的普通选择查询

    选择 ClientId、InvoiceId、IsPaid来自客户发票其中 ClientId 在 (4)和 InvoiceId 在 (34,35)

最佳答案

查看您分析的 SQL:

exec sp_executesql
N'SELECT ClientId, InvoiceId, IsPaid
FROM ClientInvoice
WHERE ClientId IN ( (@ClientIds1) )
AND InvoiceId IN ( (@InvoiceIds1,@InvoiceIds2) )',
N'@InvoiceIds1 int,@InvoiceIds2 int,@ClientIds1 bigint',InvoiceIds1=35,InvoiceIds2=34,ClientIds1=4

我们可以看到您在 @ClientIds1 周围有两组括号和 @InvoiceIds1,@InvoiceIds2 ,您编写的集合,以及 Dapper(或其下方的层)正在注入(inject)的集合。

因此,尝试删除您添加的括号:

string sqlQuery = "SELECT ClientId, InvoiceId, IsPaid " +
"FROM ClientInvoice " +
"WHERE ClientId IN @ClientIds " +
"AND InvoiceId IN @InvoiceIds";

这与 Dapper README 中的代码匹配:

Dapper allows you to pass in IEnumerable<int> and will automatically parameterize your query.

For example:

connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 } });

Will be translated to:

select * from (select 1 as Id union all select 2 union all select 3) as X where Id in (@Ids1, @Ids2, @Ids3)" // @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3

关于c# - Dapper 和列表参数在 ',' 附近返回不正确的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65196925/

26 4 0
文章推荐: python - 将任何 ASCII 字符串唯一编码为使用 ASCII 子集的字符串
文章推荐: python - 有没有办法在 python 中使用 selenium 获取
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com