Generic Locate Method, using ADO.NET and Procedures

Asked

Viewed 240 times

2

I am looking for a solution from a generic repository to a DAL with a generic Find method, so there is no redundancy in my code. Using ADO.NET and Procedures.

I found something in this link:

What would be the best way to make a CRUD for a framework in the most generic way possible?

Generic signature:

List Selecionar(IEnumerable operadores);

But I didn’t quite understand how to work with this list of operators.

Since I will use Procedure by passing the parameters to my Procedure, there is some practical way for me to pass the operators to my Procedure in a generic way using ADO.NET?

1 answer

2


Yes, it would actually work analogously.

Suppose the method List Selecionar(IEnumerable operadores), requested as an example:

public override List<MeuObjeto> Selecionar(IEnumerable<Operadores.Operador> operadores)
{
    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("spMinhaSpDeSelecao", con);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;

        foreach (var operador in operadores)
        {
            cmd.Parameters.AddWithValue("@" + operador.Nome, operador.Valor);
        }

        SqlParameter valorSaida = new SqlParameter();
        valorSaida.ParameterName = "@ValorSaida";
        valorSaida.SqlDbType = System.Data.SqlDbType.Int;
        valorSaida.Direction = System.Data.ParameterDirection.Output;
        cmd.Parameters.Add(valorSaida);

        con.Open();
        var reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            yield return new MeuObjeto 
            {
                Campo1 = reader["Campo1"].ToString(),
                Campo2 = reader["Campo2"].ToString(),
                Campo3 = reader["Campo3"].ToString(),
                ...
            };
        }

        reader.Close();
    }
}
  • Nice guy, you gave me a good look at your code. But one thing, before passing the Operators List to the method you popularized this List with parameters like ? Pq the method receives a list of the fixed type Operator already with the parameters set in that list.

  • @Franciscoproença See in the other answer the method ExtrairParametros. I think it’ll help.

Browser other questions tagged

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