问题
I'm attempting to use dapper and pass into a stored procedure a list of integers which I have defined here using DDL
CREATE TYPE [dbo].[BrandIDSet] AS TABLE ([BrandID] INT NULL);
I've created this stored procedure:
CREATE PROCEDURE dbo.usp_getFilteredCatalogItems
@BrandIDSet [dbo].[BrandIDSet] READONLY
and attempting to pass in in c# code the value for that parameter as
public async Task<PaginatedCatalogItemsVM> GetFilteredCatalogItems(int pageSize, int pageNumber, List<int> brandIDSet)
{
..
string storedProcName = "dbo.usp_getFilteredCatalogItems";
paginatedItemsVM.CatalogItemResults = await connection.QueryAsync<CatalogItemVM>(storedProcName, new { BrandIDSet = brandIDSet }, commandType: CommandType.StoredProcedure);
However, dapper does not seem to be converting the list as expected. With the above code, it results in the following SQL getting executed
exec dbo.usp_getFilteredCatalogItems @BrandIDSet1=1
Which isn't right, since BrandIDSet1 is not the name of the parameter. Arg. Thus, it results in
SqlException: @BrandIDSet1 is not a parameter for procedure usp_getFilteredCatalogItems.
How do I get the type to convert to the proper SQL?
回答1:
You can pass DataTable for proper result. You can try the code below;
var dt = new DataTable();
dt.Columns.Add(new DataColumn("BrandID", typeof(int)));
foreach (var id in brandIDSet)
{
var row = dt.NewRow();
row["BrandId"] = id;
dt.Rows.Add(row);
}
string storedProcName = "dbo.usp_getFilteredCatalogItems";
paginatedItemsVM.CatalogItemResults = await connection.QueryAsync<CatalogItemVM>(storedProcName, new { BrandIDSet = dt }, commandType: CommandType.StoredProcedure);
来源:https://stackoverflow.com/questions/52683331/using-dapper-how-do-i-pass-in-the-values-for-a-sql-type-as-param