Dynamic Search in C # and WPF

3

Good morning

I would like to ask you a question about a dynamic search.

Scenario:

I have a search screen where the user selects 3 fields, which are:

  • The first is the field of the search screen, where you select which field you want to fetch the value from.
  • The second is the condition where you can select the values = Containing, Starting, Finishing, or Equal
  • The third would be the value that he wants to search
  • Screen example:

    SohowwouldyoubestdevelopthisinC#?

    • Createdropdownwithfieldvaluesandconditions.ThencreateamethodwhereIgetthevaluesinformedandthusgenerateaswitchcasewiththeconditionsdata?moreorlessthisway:

    ->

    publicClientepesquisarCliente(stringcondicao,stringcampo,stringvalor){stringoperador="";
                string sql;
                switch(condicao)
                {
                    case "Condendo":
                        operador = "LIKE %"+ valor +"%";
                        break;
                    case "Iniciando":
                        operador = "LIKE %"+ valor;
                        break;
                    case "Terminando":
                        operador = "LIKE "+ valor +"%";
                        break;
                    case "Igual":
                        operador = " = "+ valor;
                        break;  
                }
                sql = "SELECT * FROM CLIENTES where @campo "+valor;
                Com = new NpgsqlCommand (sql);
               } 
    

    Would that be the best way? Would anyone else have developed this?

    I do not know if I was clear in my doubt.

    Thank you in advance for your attention.

    I'm developing in C # layers with WPF and PostgreSQL database; I have the layers DAL, BLL, GUI and Model

        
    asked by anonymous 20.03.2017 / 15:49

    3 answers

    1

    Good morning.

    I would do the screen only with the "value" and with the "fields" that should be used for the search. Something like the following:

    All"fields" selected by the user would be added to a list, and the pesquisarCliente method would look like this:

    public List<Cliente> pesquisarCliente(string valor, List<string> campos)
    {
        string sql;
    
        string where = "";
        for (int i = 0; i < campos.Count(); i++)
        {
            where += string.Format("{0} LIKE '%{1}%'", campos[i], valor);
            if (i < campos.Count() - 1)
            {
                where += " OR ";
            }
        }
    
        sql = string.Format("SELECT * FROM Clients WHERE ({0});", where);
    
        // Executar sql aqui e retornar lista com clientes encontrados
    }
    
        
    20.03.2017 / 20:46
    0
    //Metodo Pesquisar elo artigo
    public static List<Cliente> Pesquisar_Artigo(string condicao, string campo, string    valor)
    {
        string cn = Properties.Settings.Default.SGV;
        SqlConnection conexao = new SqlConnection(cn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conexao;
        cmd.CommandType = CommandType.Text;
    
        //Faz o teu case aqui
        cmd.CommandText = pesq;
    
        //Aqui faz o teu parametro
        ex.: cmd.Parameters.AddWithValue("@Cliente", Nome);
        conexao.Open();
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        List<Cliente> Pesquisa = new List<Cliente>();
        if (dr.Read())
        {
            //Instacia a classe e depoius adciona todos os atributos ex.: 
            Ciente obj = new Cliente();
            obj.id_cliente = Convert.ToInt32(dr["id_cliente"].ToString());
            obj.Nome = dr["Nome"].ToString();
    
            Pesquisa.Add(obj);
        }
        return Pesquisa;
    }    
    
        
    20.03.2017 / 16:27
    0

    Uses Entity Framework + npgsql works 100% and you make all kinds of queries you need

    PostgreSql + EntityFramework a necessary change (I do not know if it is more after so much time that I use) is to add the OnModelCreating in your Context class which is the default database schema (I think this does not have in the article)

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.HasDefaultSchema("public");
    }
    

    Query example:

    public List<Pessoa> ListarPaginado(string noDoc, string nome, string email, int currentPage, int pageSize, out int totalPaginas)
        {
            var pagina = (currentPage - 1) >= 0 ? (currentPage - 1) : 0;
            if (pageSize <= 0) pageSize = 1;
    
            using (var db = new MeuContext())
            {
                var total = db.Pessoas.Count(x =>
                    (
                        !string.IsNullOrEmpty(noDoc)
                        ? x.Documentos.Any(d => d.NoDoc.Contains(noDoc))
                        : x.Id > 0
                    )
                    &&
                    (
                        !string.IsNullOrEmpty(email)
                        ? x.Email.Contains(email)
                        : x.Id > 0
                    )
                    &&
                    (
                        !string.IsNullOrEmpty(nome)
                        ? x.Nome.Contains(nome)
                        : x.Id > 0
                    )
                    && x.Id > 1 //Não mostra o Admin
                );
                totalPaginas = total % pageSize > 0 ? (total / pageSize) + 1 : total / pageSize;
    
                return db.Pessoas.Where(x =>
                    (
                        !string.IsNullOrEmpty(noDoc)
                        ? x.Documentos.Any(d=>d.NoDoc.Contains(noDoc))  
                        : x.Id > 0
                    )
                    &&
                    (
                        !string.IsNullOrEmpty(email)
                        ? x.Email.Contains(email)
                        : x.Id > 0
                    )
                    &&
                    (
                        !string.IsNullOrEmpty(nome)
                        ? x.Nome.Contains(nome)
                        : x.Id > 0
                    )
                    && x.Id > 1 //Não mostra o Admin
                )
                .Include(x=>x.Documentos)
                //.Include(x=>x.Enderecos)
                .OrderBy(x => x.Nome)
                //.ThenBy(x => x.NoDoc)
                .Skip(pagina * pageSize)
                .Take(pageSize)
                .ToList();
            }
        }
    
        
    11.04.2017 / 20:38