I am using Dapper to make a call to a stored procedure. I would like to use the returned record outside of the using statement but I am not sure how to declare the variable returnedData
as it is dynamic and dependent on the results of the stored procedure. I am only making this call once so it does not make any sense to me to make a model to represent the collection returned by the stored procedure, hence why I wanted to use .
using (IDbConnection db = new SqlConnection(SqlDataAccess.LoadConnectionString("TestData")))
{
var returnedData = db.Query<dynamic>("StoredProcedureName",
new
{
ClientId = myClientId,
CompanyId = myCompanyId
},
commandType: CommandType.StoredProcedure).SingleOrDefault();
}
How to a declare the variable returnedData
before the using
statement so the compiler will be happy?
Query<T>
returns IEnumerable<T>
, and SingleOrDefault
produces a T
from it, so returnedData
can be declared as dynamic
:
dynamic returnedData = null;
using (IDbConnection db = new SqlConnection(SqlDataAccess.LoadConnectionString("TestData")))
{
returnedData = db.Query<dynamic>(
"StoredProcedureName"
, new {
ClientId = myClientId
, CompanyId = myCompanyId
}
, commandType: CommandType.StoredProcedure
).SingleOrDefault();
}
Console.WriteLine(
"ClientId={0}, CompanyId={1}"
, returnedData?.ClientId
, returnedData?.CompanyId
);