【问题标题】:Pass output parameters in a template object in Dapper在 Dapper 的模板对象中传递输出参数
【发布时间】:2018-10-11 02:26:36
【问题描述】:

我有带有输入和输出参数的存储过程。我有单独的输入和输出类。所以,我想使用模板对象创建动态参数,而不是添加每个属性。

例如:

public class StudentInput {
 public StudentInput() {
   this.StudentId = 1;
 }
 public int StudentId {get; set}
}

public class StudentOutput {
 public string StudentName {get; set;}
 public string FavSubject {get; set;}
 public int Grade {get; set;}
 public int YearOfJoining {get; set;}
}

我有一个存储过程 [SP_GetStudentData],它将 StudentId 作为输入并返回 StudentName、FavSubject、Grade 和 YearOfJoining。

使用 Dapper,我编写了以下代码。

DynamicParameters ip = new DynamicParameters(new StudentInput());
DynamicParameters op = new DynamicParameters(new StudentOutput());

ip.AddDynamicParameters(op); 

// Here is the question. How do I tell Dapper that op is a output parameters object? How do I add ParameterDirection output to each of the properties in this object?

SqlMapper.ExecuteSP(connection, SP_GetStudentData, ip, CommandType.StoredProcedure)

【问题讨论】:

    标签: c# .net dapper dynamicparameters


    【解决方案1】:

    问题是 SQL Server 只能返回标量对象作为输出参数。因此,您无法将输出参数映射到您的 StudentOutput 类。只需将您需要的值作为结果集返回(使用 SP 中的 SELECT 语句),然后将该结果集映射到您的类。

    var result = connection.Query("SP_GetStudentData @studentId", new { studentId = (new StudentInput()).StudentId }, commandType:StoredProcedure)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-16
      • 2021-11-24
      • 1970-01-01
      • 2022-12-13
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多