Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple parameters with SqlParameter

I know how to pass one parameter to an sql query but i want to create a function to pass multiple params that will have differents type and here im stuck.

public List<T> RawSql<T>(string query,  params object[] parameters)
{
    var command = context.Database.GetDbConnection().CreateCommand();

    command.CommandText = query;
    command.CommandType = CommandType.Text;

    SqlParameter parameter = new SqlParameter();
    parameter.ParameterName = "@bookId";
    parameter.SqlDbType = SqlDbType.Int;

    parameter.Value = parameters[0];

    command.Parameters.Add(parameter);

    var result = command.ExecuteReader())

    return result;
}

Usage :

var rows = helper.RawSql("myStoreProc @bookId", x=> new Book { Id = (bool)x[0] }, bookId);

But how i can change the RawSql function to pass multiple parameters like this :

var rows = helper.RawSql("myStoreProc @bookId, @authorName", x=> new Book { Id = (bool)x[0] }, bookId, authorName);
like image 555
lory Avatar asked Apr 24 '26 22:04

lory


1 Answers

I would also suggest using Dapper instead of reinventing the wheel - but if you can't for some reason, I would change the method signature to accept params SqlParameter[] parameters instead of params object[] parameters - and then all you need to do in the method is command.Parameters.AddRange(parameters);.

As Marc Gravel wrote in his comment - naming the parameters is going to be the biggest problem if you are simply using object[].

like image 82
Zohar Peled Avatar answered Apr 26 '26 11:04

Zohar Peled