'必须声明标量变量“@SKU”。'

问题描述 投票:1回答:2

我正在使用dapper插入数据库,一直在查看我的代码,找到发生了什么,找不到任何与众不同的东西。

代码使用SELECT语句,但是当我执行插入时,我总是得到错误:

System.Data.SqlClient.SqlException:'必须声明标量变量“@SKU”。

当我从数据库,类,函数和过程中删除第一个参数时,我总是得到第一个参数的相同错误。

public class Products
{
    public string SKU;
    public string Title;
    public string ImageLink;
}

使用dapper函数插入:

public void insertItem(Products newProduct)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("SellersDB")))
    {
        List<Products> dbnewProduct = new List<Products>();
        dbnewProduct.Add(newProduct);

        connection.Execute("dbo.Item_Insert @SKU, @Title, @ImageLink", dbnewProduct);
    }
}

程序,流程:

CREATE PROCEDURE [dbo].[Item_Insert]

@SKU nchar(10),
@Title nchar(100),
@ImageLink nchar(50)

AS
BEGIN
SET NOCOUNT ON;

insert into dbo.ProductsTable (SKU, Title, ImageLink) values (@SKU, @Title, @ImageLink);

END

数据库:

CREATE TABLE [dbo].[ProductsTable] (

[SKU]       NCHAR (10)  NULL,
[Title]     NCHAR (100) NULL,
[ImageLink] NCHAR (50)  NULL
);

错误发生在激动线上。

c# sql dapper
2个回答
2
投票

Dapper想要属性,而不是领域;尝试:

public class Products
{
    public string SKU {get;set;}
    public string Title {get;set;}
    public string ImageLink {get;set;}
}

然后再试一次;你只需要传递单个对象 - 这里不需要列表。如果你选择的话,你可以将它与CommandType.StoredProcedure方法结合起来(如MarcinJ所述) - 但是要注意这会将位置参数传递(在原始问题中)传递给命名参数传递 - 所以一定要检查这不会改变含义。


1
投票

使用Dapper调用存储过程的方法是:

connection.Execute("Item_Insert", dbnewProduct, commandType: CommandType.StoredProcedure);

此外,您不需要列表,您可以在那里使用newProduct

© www.soinside.com 2019 - 2024. All rights reserved.