存储过程不返回带有动态查询的行,Dapper

时间:2018-07-16 16:10:13

标签: c# sql-server stored-procedures dapper

我已经用动态查询创建了一个存储过程。值将通过Dapper用C#返回到我的应用。

以下代码有效,这些行返回到我的应用程序,并显示在SQL Server中。

set @query = 'Select * from invoices';
exec sp_executesql @query

但是当我建立查询时,是这样的:

动态查询版本:

'SELECT * FROM Invoices AS i    
 LEFT JOIN InvoiceInformations AS ii ON i.InvoiceId = ii.InvoiceId  
 WHERE 1 = 1';

exec sp_executesql @query

在SQL Server中正确显示了行,但是在C#中,我什么也没得到。

重要的是要说它只有在动态构建查询时才会发生,但是查询没问题,我打印了它,手动运行它就可以了。

C#代码(可行):

var invoices = await dbConnection.QueryAsync<Invoices>("sp_get_invoices", commandType: CommandType.StoredProcedure);

请帮助!

1 个答案:

答案 0 :(得分:1)

我已经解决了它,我正在查找存储过程,但是还可以。 问题出在Dapper的参数上。

我有一些不能为空的值,例如InvoiceId

var invoices = await dbConnection.QueryAsync<Invoices>("sp_get_invoices",
                    new 
                    {
                        InvoiceId = filter.InvoiceId,
                        Currency = filter.Currency
                    }, commandType: CommandType.StoredProcedure);

我的存储过程验证:

if (InvoiceId IS NOT NULL)
  SET @Query = @Query + ' AND i.InvoiceId = ' + CAST(@InvoiceId as varchar(10));

我只是在C#上将其清空

        public int? InvoiceId { get; set; }