10

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?

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

0

Hopefully this will save someone time. I like Majedur's answer for more sql-like control over in/out params.

The quick and easy lesson is that Dapper's .Query<>() and .QueryAsync<>() methods do take an object that it will convert to sql parameters - with a few points to note:

Anonymous types are fine:

new { Id = 100, Name = "name" }

Other defined types will only work if their properties have getters and setters:

public class MyArg
{
    public long Id { get; set; }
    public string Name { get; set; }
}

i.e. NOT:

public class MyArg
{
    public long Id;
    public string Name;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.