Pradeep K
Pradeep K

Reputation: 317

Convert stored procedure output from dapper.net into List

I am new to Dapper.net, I am trying to execute a stored procedure using Dapper.Net.

I have a model class StoredProcedureResult, related the stored procedure's output.

public StoredProcedureResult
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
}

conn.Query(SP_name, Param(s), Type). 

The output of the model is retrieved dynamic.

After executing I get the following

{{Dapper,Name='Pradeep',Address='UK',PhoneNumber='+4478923984'}}
{{Dapper,Name='Jack',Address='USA',PhoneNumber='+447242344234}}
{{Dapper,Name='Ram',Address='UK',PhoneNumber='+447892423484'}}

I require to convert the dynamic output in List<StoredProcedureResult> structure.

After few search I found this code

conn.Query<*Model_name*>(SP_name, Param(s), Type). 

Unfortunately this return the right number of rows but the rows are empty. How can I convert the output into a List<StoredProcedureResult>.

Thanks

Upvotes: 5

Views: 10347

Answers (1)

G Davison
G Davison

Reputation: 1099

You need to specify the return type of the data when you call the Query.

  • Where you have <Model Name> is where you'd put the expected return type - .
  • In your example you're getting data back in dapper's internal dynamic dapperrow type
// Gets results in dapper's DapperRow type. 
// This is what you're getting now. 
var results = _connection.Query("SP_name", 
                      commandType: CommandType.StoredProcedure);

The example below shows returning the results in your named type which is what you actually want.

// Gets results in your type. Note we tell dapper 
// we want it turned into StoredProcedureResults.
List<StoredProcedureResult> castResults;
castResults = _connection.Query<StoredProcedureResult>(
                   "SP_name", 
                   commandType: CommandType.StoredProcedure).ToList();

Upvotes: 9

Related Questions