Get values from a query sql stringbuilder in c #

1

How could I get the data that this query throws at me and keep them in a variable?

System.Text.StringBuilder sqlidos = new System.Text.StringBuilder();
                sqlidos.Append("select td.id_traslado,td.id_traslado_detalle,td.id_articulo,ar.nombre,ar.modelo,ar.referencia,ar.codigo1,ar.codigo2 from traslado_detalle td ");
                sqlidos.Append("inner join articulo ar on ar.articuloid = td.id_articulo  ");
                sqlidos.Append("where td.id_traslado_detalle = @p0 ");

I've tried it in the following two ways but I can not get it

form 1:

var registros = db.Database.SqlQuery<Traslados>(sqlidos.ToString()).ToList();

form 2:

var registros = db.Database.SqlQuery(sqlidos.ToString(),new SqlParameter("@p0", 1)).ToList();

in the second form generates error that has invalid arguments

Error   1   La mejor coincidencia de método sobrecargado para 'System.Data.Entity.Database.SqlQuery(System.Type, string, params object[])' tiene algunos argumentos no válidos
    
asked by Andrex_11 27.11.2018 в 16:18
source

1 answer

2

In your form1: Missing the parameter.

var registros = db.Database.SqlQuery<Traslados>(sqlidos.ToString(),new SqlParameter("@p0", 1)).ToList();

In your form2: Since you did not use the generic Method SqlQuery<TSource> , then you must pass the data type to map the method as the first argument.

var registros = db.Database.SqlQuery(typeof(Traslados), sqlidos.ToString(),new SqlParameter("@p0", 1)).ToList();

Based on your class Traslados you have the properties to be mapped I put this code for you to try:

string query = @"
    select
        td.id_traslado,
        td.id_traslado_detalle,
        td.id_articulo,
        ar.nombre,
        ar.modelo,
        ar.referencia,
        ar.codigo1,
        ar.codigo2
    from
        traslado_detalle td
    inner
        join articulo ar on ar.articuloid = td.id_articulo
    where
        td.id_traslado_detalle = @p0
    ";

List<Traslados> registros1 = db.Database.SqlQuery<Traslados>(query, SqlParameter("@p0", 1)).ToList();

List<Traslados> registros2 = db.Database.SqlQuery(typeof(Traslados), query, SqlParameter("@p0", 1)).ToList();
    
answered by 27.11.2018 / 17:48
source