Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send SqlParameter to Dapper

Tags:

c#

dapper

I' using Dapper in my project. I have a list of SqlParameters and I want to send it to Dapper. But Dapper needs an object (name, value). How can I convert a SqlParameter to an object. I know this doesn't work:

conn.Query<TModel>(sql, parameters.Select(p => new {p.ParameterName=p.Value}))

any suggestions?

like image 720
Mahmood Dehghan Avatar asked Apr 10 '14 04:04

Mahmood Dehghan


2 Answers

Stumbled across this looking for something else - but can offer some insight that may help others in the future.

You can use the Dapper.DynamicParameters object to add items that can be legally passed to Dapper Queries, i.e. (hand-coded)

var args = new DynamicParameters(new {});
parameters.ForEach(p => args.Add(p.ParameterName, p.Value));
conn.Query<TModel>(sql, args );

HTH

like image 199
SeanCocteau Avatar answered Nov 17 '22 06:11

SeanCocteau


In addition You can also assign direction of your input parameters, data types,

var parameters = new DynamicParameters();
parameters.Add(name: "@UserId", value: obj.DriverId, dbType: DbType.String, direction: ParameterDirection.Input);
parameters.Add(name: "@Password", value: obj.DPassword, dbType: DbType.String, direction: ParameterDirection.Input);
parameters.Add(name: "@IMEINo", value: obj.IMEINo, dbType: DbType.String, direction: ParameterDirection.Input);
return DatabaseHub.Query<object>(storedProcedureName: @"[dbo].[sp_m_GetAppLoginCheckData]", parameters: parameters, dbName: AMSDB).FirstOrDefault();
like image 41
Majedur Avatar answered Nov 17 '22 07:11

Majedur