Take value of a field from an identifier of a table

0

I have the following instructions with which I intend to obtain a value of a field from an identifier of a table.

  idFac = Convert.ToDecimal(Request.QueryString["id"]);//Capturo el Id del registro
         sql.Append("SELECT codigo from factura");//aplico la query
         sql.Append("WHERE id_factura=idFac");
         var registro = db.Database.SqlQuery<factura>(sql.ToString(),idFac);//almaceno la query en la variable registro

   var querycredifact = db.creditoes.Where(s => s.codigo == Convert.ToDecimal(registro)); //intento mostrar lo que hay en la query
   objcre = querycredifact.FirstOrDefault();

What I intend to do is obtain or reference the codigo field that you selected in the query, so that you can count on that value to indicate that it is the same in another table.

// what I need is that querycredifact equals the existing value in the field codigo

I do not know what I'm failing!

    
asked by Andrex_11 19.09.2018 в 18:51
source

1 answer

1

You could do something like this

idFac = Convert.ToDecimal(Request.QueryString["id"]);

string sql = "SELECT codigo from factura WHERE id_factura=idFac";
var registro = db.Database.SqlQuery<decimal>(sql, idFac).FirstOrDefault();

var objcre = db.creditoes.FirstOrDefault(s => s.codigo == registro);

As you will see to obtain a simple value you do not need to cast the SqlQuery to an invoice, but you do it directly to a simple data type.

Then instead of using the Where() you can apply the direct filter to FirstOrDefault()

Execute Raw SQL Queries in Entity Framework 6

Check how you assign the parameter, maybe you have to use something like this:

string sql = "SELECT codigo from factura WHERE id_factura=@idFac";
var registro = db.Database.SqlQuery<decimal>(sql, new SqlParameter("@idFac", idFac)).FirstOrDefault();
    
answered by 19.09.2018 / 19:03
source