Store values of a query in a variable

0

I am applying the following query to get the value of an existing field in a table and capture it in a variable.

var captbarras = TextBoxLeerSerial.Text;
            string sqli = "SELECT codigobarras from articulo WHERE codigobarras='captbarras'";
            var obtenerarticulos = db.Database.SqlQuery<string>(sqli).FirstOrDefault();

            if (obtenerarticulos == TextBoxLeerSerial.Text)
           {
                ScriptManager.RegisterStartupScript(this, this.GetType(),
                "alert",
                "alert('No se ha podido actualizar el codigo de barras, este codigo ya se utiliza');window.location ='/Aspx/Compras/CargarSeriales.aspx';",
                true);
            }

What I need to do is get the value that exists in the field I select and get it in the variable obtenerarticulos my big drawback is that I do not capture any value and the value I enter in the textbox TextBoxLeerSerial if it exists.

The data type of the codigobarras field in the DB is varchar

and in case that value does not exist, apply for the else ...

    
asked by Andrex_11 21.09.2018 в 16:04
source

1 answer

2

You have to assign the parameter to the SELECT to apply the filter, since currently you are only looking for the codes that they have

string sqli = "SELECT COUNT(*) from articulo WHERE codigobarras= @codigo";
var cantidad = db.Database.SqlQuery<int>(sqli, new SqlParameter("@codigo", captbarras)).FirstOrDefault();

if(cantidad > 0) {

    ScriptManager.RegisterStartupScript(this, this.GetType(),
            "alert",
            "alert('No se ha podido actualizar el codigo de barras, este codigo ya se utiliza');window.location ='/Aspx/Compras/CargarSeriales.aspx';",
            true);
}

Pay attention to how the

is used
new SqlParameter("@codigo", captbarras)

when running the sql query

If you want to know if the code is already being used, recover the number of records according to the filter and not the code as a string because this would not indicate whether it exists or not, well unless you validate that a NULL returns

Execute Raw SQL Queries in Entity Framework 6

    
answered by 21.09.2018 / 17:55
source