Can not find the parameter passed to the insert command

2

I'm developing a web application in ASP.NET and am wanting to insert data into a table in the database, but specifying the parameter displays the following error in the line of cmd.Parameters.AddWithValue("@codigo", this._codigo); :

  

Client does not contain definition for "_codigo", it was not possible to find any extension method "_codigo" that accepts an argument of type Client

   public partial class Cliente : IDisposable
    {

    public Cliente()
    {


    }

 public void gravar() {

        SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|C:\Users\Antonio Viana\documents\visual studio 2017\Projects\Loja\Eccomerce\App_Data\dados.mdf;Integrated Security=True");
        {
            try
            {
                cn.Open();
            }
            catch (Exception)
            {

                throw;
            }


            using (SqlCommand cmd = new SqlCommand())
            {

                cmd.CommandText= "Insert Into Cliente (codigo,nome,email,sexo,estado,senha,data,celular,cpf,cidade,cep,confirmar, rua,numero,bairro,uf,login,telefone) values(@codigo,@nome,@email,@sexo,@estado,@senha,@data,@celular,@cpf,@cidade,@cep,@confirmar,@rua,@numero,@bairro,@uf,@login,@telefone)";
                cmd.Connection = cn;

                cmd.Parameters.AddWithValue("@codigo", this._codigo);

                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception)
                {

                    throw;
                }

            }

        }

    }
    }

    public partial class Cliente
    {

    private int _codigo;
    public int Codigo
    {

        get { return _codigo; }//busca o valor do codigo
        set {
            if(value<0)
            {
                throw new Eccomerce.Excecoes.ValidacaoException("O codigo do 
           cliente não pode ser negativo");
                _codigo = 0;
            }

            _codigo = value; }
       }



    private String _nome;
    public String Nome
    {

        get { return _nome; }
        set
        {
            if (value.Length<=10)
            {
                throw new Eccomerce.Excecoes.ValidacaoException("O nome deve ter no minimo 3 10 caracteres");
                _nome = value;
            }


        }
    }


    public String email { get; set; }
    public String sexo { get; set; }
    public String estado { get; set; }
    public String senha { get; set; }
    public String data { get; set; }
    public String celular { get; set; }
    public String cpf { get; set; }
    public String cidade { get; set; }
    public String cep { get; set; }
    public String confirmar { get; set; }
    public String rua { get; set; }
    public String numero { get; set; }
    public String bairro { get; set; }
    public String uf { get; set; }
    public String login { get; set; }
    public String telefone { get; set; }

}

Project Hierarchy

    
asked by anonymous 18.07.2017 / 23:20

2 answers

3

The code is very confusing and until the compiler is not understanding, try to do this:

public class Cliente {
    public Cliente() {} //tem certeza que quer impedir a construção?

    public void gravar() {
        var cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|C:\Users\Antonio Viana\documents\visual studio 2017\Projects\Loja\Eccomerce\App_Data\dados.mdf;Integrated Security=True");
        cn.Open();
        using (var cmd = new SqlCommand()) {
            cmd.CommandText= "Insert Into Cliente (codigo,nome,email,sexo,estado,senha,data,celular,cpf,cidade,cep,confirmar, rua,numero,bairro,uf,login,telefone) values(@codigo,@nome,@email,@sexo,@estado,@senha,@data,@celular,@cpf,@cidade,@cep,@confirmar,@rua,@numero,@bairro,@uf,@login,@telefone)";
            cmd.Connection = cn;
            cmd.Parameters.AddWithValue("@codigo", this._codigo);
            //... aqui terá os outros campos, certo?
            cmd.ExecuteNonQuery();
        }
    }
    private int _codigo;
    public int Codigo {
        get { return _codigo; }
        set {
            if (value < 0) {
                throw new Eccomerce.Excecoes.ValidacaoException("O codigo do cliente não pode ser negativo"); //vai lançar exceção mesmo?
                _codigo = 0;
            }
            _codigo = value;
        }
    }
    private String _nome;
    public String Nome 
        get { return _nome; }
        set {
            if (value.Length <= 10) {
                throw new Eccomerce.Excecoes.ValidacaoException("O nome deve ter no minimo 3 10 caracteres");
                _nome = value;
            }
        }
    }
    public String email { get; set; }
    public String sexo { get; set; }
    public String estado { get; set; }
    public String senha { get; set; }
    public String data { get; set; }
    public String celular { get; set; }
    public String cpf { get; set; }
    public String cidade { get; set; }
    public String cep { get; set; }
    public String confirmar { get; set; }
    public String rua { get; set; }
    public String numero { get; set; }
    public String bairro { get; set; }
    public String uf { get; set; }
    public String login { get; set; }
    public String telefone { get; set; }
}

I placed GitHub for future reference .

If not, there are problems in configuring the project for the project.

I gave a good cleanup, taking unnecessary things like IDisposable , catch exception that does nothing, but could have other things better. I deleted the partial class that I saw no advantage in it. Just use what you know how to use and have a good explanation to use.

It would be interesting to maintain a pattern. To use _codigo , if codigo is enough. This is often not indicated as nomenclature in C # . Because Codigo property is in uppercase, and should it be, and email is lowercase? Be consistent.

    
18.07.2017 / 23:49
2

You have a lot of "improvement opportunities" in your code.

Partial Class

What's in ClientDAO ? Why did you create a class partial Cliente ? What motivation? If it were an abstract, you can have several types of clients, yes, but partial ? I do not think this is the path you would like to follow.

Try..Catch

If nothing is good to do this:

try
{
    // codigo
}
catch (Exception) // nada está sendo capturado aqui
{
    throw; // a exceção não está sendo tratada, apenas jogada.
}

If it is to do this, just leave the code, which is the exception, this will do the bubble up natively.

Repository - DAO

Do not mix responsibility. Your Cliente entity should not know database. Just do it:

public class Cliente
{
    public string Login {get;set;}
    public string Email {get;set;}
    // outras propriedades
}

And a repository - formerly known as DAO - which will try to persist and retrieve data from your client.

public class ClienteRepositorio
{
    private readonly IDbConnection _connection;

    public ClienteRepositorio(IDbConnection connection)
    {
        _connection = connection;
    }

    public void Gravar(Cliente cliente)
    {
        using (var cmd = connection.CreateCommand()) 
        {
            cmd.CommandText= "INSERT INTO Cliente (...) VALUES (...)";
            cmd.Parameters.AddWithValue("@codigo", this._codigo);
            cmd.ExecuteNonQuery();
        }            
    } 
}

Bad use of IDisposable

If you use IDisposable when it is important to perform operation when your object is destroyed. Example: Before destroying a connection object, you must ensure that the connection is closed.

In the code you posted, you have IDisposable, but you do not have the implementation of the Dispose() method, so I assume something is missing.

Object contains no definition for "name",

Considering that your query has several parameters, but in the example you only posted one, I understand that you have not published all of them in order not to create a "polluted" question, but I believe the problem is in the other parameters - typing.

    
19.07.2017 / 14:16