【问题标题】:Returning Output Parameters with Dapper for .NET Core使用 Dapper for .NET Core 返回输出参数
【发布时间】:2016-12-14 19:14:19
【问题描述】:

当我从模板对象创建 DynamicParamters 时,我正在努力解决如何使用 Dapper 将输出参数正确映射回对象。

var parameters = new DynamicParameters(entity);
parameters.Add("@Id", dbType: DbType.Int32, direction: ParameterDirection.Output);
parameters.Output(entity, x => x.Id);             

await conn.ExecuteAsync(
   "TodoItemInsert", entity, 
    commandType: CommandType.StoredProcedure);  

我希望上面的代码将生成的 ID 映射回我最初创建参数的实体。无论我尝试什么,我都无法从存储过程中获取要返回的参数。调用parameters.Get<int>("@Id") 会抛出KeyNotFoundExceptionparameters.Get<int?>("@Id") 返回 null。

我的 SQL 是一个非常基本的插入存储过程

ALTER PROCEDURE [dbo].[TodoItemInsert]
    @Name VARCHAR(255)
    , @Description VARCHAR(512)
    , @DueDate DATETIME = NULL
    , @IsComplete BIT = 0
    , @Id INT OUTPUT 
AS

INSERT INTO
    [TodoItems]
(
    Name
    , Description
    , DueDate
    , IsComplete
)
VALUES
(
    @Name
    , @Description
    , @DueDate
    , @IsComplete
)

SET @Id = SCOPE_IDENTITY()

尝试为我的DynamicParameters 使用对象模板时,从 Dapper 获取输出参数的正确方法是什么?

【问题讨论】:

    标签: dapper .net-core


    【解决方案1】:

    想通了,当我从模板转移到参数时,没有正确更新我的代码。我将entity 传递到我的查询中,而不是parameters。一旦我替换它,我什至可以摆脱 Id 输出参数的显式添加。这个好看多了!

    var parameters = new DynamicParameters(entity);
    parameters.Output(entity, x => x.Id);             
    
    await conn.ExecuteAsync(
       "TodoItemInsert", parameters, 
        commandType: CommandType.StoredProcedure);  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 2022-12-13
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多