Avoid duplicate values C #

0

Good I would like to ask you a question, how can I do to verify that the value written in a textbox is not repeated in the table of the database this would be a portion of the code that is in the presentation layer before being Sent to the method insert in the business logic.

public override bool EjecutarComandoNuevo()
    {
        if (!VerificarDatosObligatorios())
        {
            MessageBox.Show(@"Por favor ingrese los campos Obligatorios.", @"Atención", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            return false;
        }

        var nuevaProvincia = new ProvinciaDto
        {
            Descripcion = txtDescripcion.Text,
        };

        _provinciaServicio.Insertar(nuevaProvincia);

        return true;
    }
    
asked by Daniel Bejar 14.11.2018 в 23:37
source

1 answer

1

You could use something like this

public bool Existe(string parametro)  
{  
    string sql = @"SELECT COUNT(*) FROM <Tabla> WHERE campo = @param";   
    using (SqlConnection conn = new SqlConnection("connection string"))   
    {   
        conn.Open();  

        SqlCommand cmd = new SqlCommand(sql, conn);   
        cmd.Parameters.AddWithValue("@param", parametro);   

        int count = Convert.ToInt32(cmd.ExecuteScalar());   

        return count == 0;   
    }   
} 

The idea is that you pass the value that identifies the entity and use it in the where of the sql, being able to see the number of records that exist, if there is none then it is not duplicated

    
answered by 15.11.2018 в 04:34