I've been using Dapper to call stored procedures passing it an object. For example:
If I have an object:
public int ID { get; set; }
public int Year { get; set; }
I can create this object and pass it to my Execute call as the parameters. Dapper automatically maps all of those properties into parameters and executes the stored procedure. Awesome.
What about output parameters? If my object looked like the following how can I get Dapper to populate that property with the output parameter value?
public int ID { get; set; }
public int Year { get; set; }
public int OutputParameter { get; set; }
Do output parameters have to be added as DynamicParameters?
Actually, the question was Do output parameters have to be added as DynamicParameters?
The answers is - no, you don't have to use DynamicParameters class. You can simply create anonymous object and fetch your output parameter value by using final SELECT query.
Assuming you a have a SP with signature dbo.MyProc @id int, @year int, @parOut int OUTPUT and your class.
class MyClass
{
public int ID { get; set; }
public int Year { get; set; }
public int OutputParameter { get; set; }
}
The call should be as follows:
MyClass myObject = new MyClass { Id = 123, Year = 2023 };
int result;
using (var connection = new SqlConnection(myConnectionString))
{
result = connection.QueryFirstOrDefault<int>(
@"dbo.MyProc @id, @year, @parOut OUTPUT; SELECT @parOut",
new
{
id = myObject.Id
, year = myObject.Year
, parOut = myObject.OutputParameter
});
myObject.OutputParameter = result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With