How to pass a list of integers as Dapper parameters?

Asked

Viewed 417 times

1

I am trying to pass a parameter which is a list of integers, this should be attached to query in the sql server IN clause, 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) ");
}

//Mounting of the parameters;

var parametros = new
{
    adesoes = adesoesids,
};

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

If I pass the string directly joins up to arrive in the form that should only of the string type where it should be integers as (1,2,3,4 ...) is going ('1,2,3,4 ..')

adesoes = string.Join(",", Adesao.Repositorio.ObterTodasAdesoes(adesao));

1 answer

2


Your first approach seems correct to me. The problem is that ids is not a list of integers but a array integer list. Also, you create an object adesoesids to put this data.

Basically, your object parametros is like this

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

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

Your code should be 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();
  • I tried to do so, but returns syntax error, if I do not mount the query with this filter it passes of good, it is something wrong in this parameter same.

  • Syntax error? What error?

  • I’ll keep using the string. Format it mounts and this normally works Sb.Appendwhere(string.Format(" e.Adesaoid IN({0}) ", string.Join(",", adhesions)));

  • There is not much specification in error only .. . Incorrect syntax near ','.

  • I think the structure of your filter object is not yet correct. This occurs when? When running the query?

  • this, if I take the part , Sb.Appendwhere(" e.Adesaoid IN (@adhesions) "); function normally .

  • I saw some solutions like, https://stackoverflow.com/questions/39523414/c-sharp-dapper-error-when-parameter-is-listint-no-mapping-exists-from-object-t and https://stackoverflow.com/questions/12723922/dapper-adddynamicparams-for-in-statement-with-dynamic-Parameter-name where they pass Arry directly as a single parameter.

  • You can show a print of the filter object structure?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.