小巧玲珑:"Insufficient parameters supplied to the command"

Dapper: "Insufficient parameters supplied to the command"

我有一个 Test 模型 class:

public class Test
{
    public string One;
    public int Two;
}

我有一个 test table:

CREATE TABLE "test" 
(
    "one"   TEXT NOT NULL,
    "two"   INTEGER NOT NULL
);

尝试执行此代码时:

using (IDbConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
    con.Execute("INSERT INTO test VALUES (@One, @Two)", new Test
    {
        One = "hello",
        Two = 123
    });
}

我收到这个错误:

code = Unknown (-1), message = System.Data.SQLite.SQLiteException (0x80004005): unknown error
Insufficient parameters supplied to the command

我什么都试过了,还是找不到原因。

Dapper 需要命令参数作为 .execute() 命令的 "Anonymous"、"string"、"List" 和 "dynamic",因此传递类型对象不是支持

using (IDbConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
    con.Execute("INSERT INTO test (one, two) VALUES (@One, @Two)", new 
    {
        One = "hello",
        Two = 123
    });
}

使用你的测试对象。

using (IDbConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
    Test tobj = new Test();
    tobj.One = "hello";
    tobj.Two = 123;

    con.Execute("INSERT INTO test (one, two) VALUES (@One, @Two)", tobj);
}

Dapper 不知道如何将您的 class 分解为两个变量。参见 https://github.com/StackExchange/Dapper/issues/540。 您可以在 Insert 语句中使用 1 个参数并传递 class,或者使用 2 个参数并传递单个参数,如下所示。

        DynamicParameters parameters = new DynamicParameters();
        parameters.Add("One", Test.One, DbType.String, ParameterDirection.Input);
        parameters.Add("Two", Test.Two, DbType.Int32, ParameterDirection.Input);

        using (IDbConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
        {
            con.Execute("INSERT INTO test VALUES (@One, @Two)", parameters);
        }