Create a method to get records by id

1

In my CRUD I want to create a method obterPorId(Cliente cli) I want to get the records by code, or by name, or another field.

How would you get the DataReader?

a correct way, using a method that returns a client, eg:

public Cliente obterPorId(Cliente cli)
    
asked by anonymous 01.02.2015 / 05:54

1 answer

2

As you did not give more information I'll put something that would work an application of mine. Of course you will have to make several adaptations, use the method appropriately or change it to take care of exceptional situations or do something other than return null if nothing is found (although in my system I would do differently).

public Cliente ObterPorId(int id) {
    using (connection) { //imagino que esta informação está disponível na classe
        using (var command = new SqlCommand("SELECT campo1, campo2 FROM Clientes WHERE Id = @id;", connection)) {
            cmd.Parameters.Add(new SqlParameter("@id", id));
            connection.Open();
            using (var reader = command.ExecuteReader()) {
                Cliente cliente;
                if (reader.Read()) {
                    cliente = new Cliente();
                    cliente.campo1 = reader.GetString(0) //primeira coluna
                    cliente.campo2 = reader.GetString(1) //segunda coluna
                }
            }
        }
    }
    return cliente;
}

@id is a query parameter, it will be replaced by the id passed to this method as SqlParameter " used below.

Obviously I did not test but the general idea is this. Reinforcing specific needs will make the algorithm be different from this. In fact this form is very simplified for some real situations. That's why the questions should have details.

Of course there are several other ways to get the same result.

    
01.02.2015 / 12:22