Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

c# - Call Procedure with parameter in postgresql using Dapper in Asp.net Core

Am new in postgresql, and I want to call stored procedure (postgresql) with some parameter in Asp.net Core web api via dapper.

Error: syntax error at or near "@"

Procedure:

CREATE OR REPLACE PROCEDURE public.usp_addbook(
    book_id integer,
    book_name text,
    book_desc text)
LANGUAGE 'plpgsql'
AS $BODY$
begin
   
   INSERT INTO book (book_id,book_name,book_desc) values (book_id,book_name,book_desc);

    commit;
end;
$BODY$;

Asp.net Core :

await WithConnection(async conn =>
{
    var p = new DynamicParameters();
    p.Add("@book_id", entity.book_id);
    p.Add("@book_name", entity.book_name);
    p.Add("@book_desc", entity.book_desc);
    
    string callSP = "CALL " + _commandText.AddBookByStoredProcedure + " (@book_id,@book_name,@book_desc)";  
    await conn.ExecuteAsync(callSP, p, commandType: CommandType.StoredProcedure);
});

protected async Task WithConnection(Func<IDbConnection, Task> getData)
{
    try
    {
        await using var connection = new NpgsqlConnection(_ConnectionString);
        await connection.OpenAsync();
        await getData(connection);
    }
    catch (TimeoutException ex)
    {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL timeout", GetType().FullName), ex);
    }
    catch (NpgsqlException ex)
    {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL exception (not a timeout)", GetType().FullName), ex);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You do not need to mention parameter name in first parameter. You have already included it in DynamicParameters instance.

Also, the CALL is not needed. Following should work properly.

string callSP = _commandText.AddBookByStoredProcedure;
await conn.ExecuteAsync(callSP, p, commandType: CommandType.StoredProcedure);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...