How to pass a list of integers as dapper parameters?

1

I am trying to pass a parameter that is a list of integers, this should be appended to query in the IN clause of the sql server, but I'm not sure how to use it with DAPPER .

I tried to do it this way.

var adesao = Adesao.Repositorio.Obter(adesaoId.Value);
if (adesao != null)
{
    adesoes = string.Join(",", Adesao.Repositorio.ObterTodasAdesoes(adesao));
    var ids = new[] { adesoes.Split(',').Select(Int32.Parse).ToList() };
    adesoesids = new { ids };

    sb.AppendWhere(" e.AdesaoId IN (@adesoes) ");
}

// Assembly of the parameters;

var parametros = new
{
    adesoes = adesoesids,
};

return SessionDapper.Query<Extrato>(sb.ToString(), parametros).ToList();

If I pass the string direct adhesions until it arrives the way it should only of the type string where it should be integers as (1,2,3,4 ...) is going ('1,2,3,4. .)

adesoes = string.Join(",", Adesao.Repositorio.ObterTodasAdesoes(adesao));
    
asked by anonymous 31.07.2017 / 15:49

1 answer

2

Your first approach seems to me correct. The problem is that ids is not an integer list but an array array . In addition, you create a adesoesids object to place this data.

Basically, your parametros object is like this

parametros: {
    adesoes: {
        ids: [
            [1, 2, 3, 4]
        ]
    }
}

Dapper expects the parameter used in the In clause to be IEnumerable .

Your code should look like this:

var ids = adesoes.Split(',').Select(Int32.Parse).ToList();

// Perceba que tirei o 'new [] { }' e que não é necessário criar um objeto

var parametros = new
{
    adesoes = ids,
};

return SessionDapper.Query<Extrato>(sb.ToString(), parametros).ToList();
    
31.07.2017 / 16:00