Create a method to get records by id

Asked

Viewed 412 times

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 other field.

How would you look with Datareader?

a correct way, using a method that returns a customer, ex:

public Cliente obterPorId(Cliente cli)

1 answer

3


As you did not give more information I will put something that would work an application of mine. Of course you will have to make several adaptations, use the method properly 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 different).

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))
    using (var reader = command.ExecuteReader()) {
        cmd.Parameters.Add(new SqlParameter("@id", id));
        connection.Open();
        Cliente cliente;
        if (reader.Read()) {
            cliente = new Cliente();
            cliente.campo1 = reader.GetString(0) //primeira coluna
            cliente.campo2 = reader.GetString(1) //segunda coluna
        }
    }
    return cliente;
}

I put in the Github for future reference.

The @id is a parameter of query, he will be replaced by id passed to this method as per SqlParameter next used.

Obviously I haven’t tested it, but the general idea is this. I stress what specific needs will make the algorithm different from this. Actually this form is very simplified for some real situations. So the questions should have details.

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

  • I believe that’s right, that @id, he’s getting the id stated in the method?

  • That’s right, you pass to the query through a declared parameter.

  • and in the add Parameters, that line ("id", id)); the quote id is what?

  • https://msdn.microsoft.com/en-us/library/0881fz2y(v=vs.110). aspx is the parameter of query that you are adding. He needs to know where he will fit the id passed by the method within the query. I edited p/ get more obvious.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.