Does not find the parameter passed to the insert command

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

Client contains no definition for "_code", it was not possible to find any extension method "_code" 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

Project

Author: Maniero, 2017-07-18

2 answers

The code is very confusing and even 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 put on GitHub for future reference.

If this is not the case, there are problems setting up the project for compilation.

I gave a good clean, taking away unnecessary things like IDisposable, catch exception that does nothing, but could have improved other things. I eliminated the partial class I didn't see any advantage in it. Only use what you know how to use and have a good explanation to use.

It would be interesting to keep a pattern. Why use _codigo, if codigo is enough. This is not usually indicated as nomenclature in C # . Because the property Codigo is uppercase, and it should be just like that, and email is lowercase? Be consistent.

 3
Author: Maniero, 2017-07-26 14:29:49

Has 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 was an abstract, then vc can have several types of clients, yes, but partial? I don't think that's the way you'd like to go.

Try..Catch

If there is no point doing this:

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

If you are going to do this, leave only the code, which if given an exception, this will make the bubble up natively.

Repository - DAO

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

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

And a repository-formerly known as DAO-that will handle persisting and retrieving 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();
        }            
    } 
}

Misuse of IDisposable

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

In the code you posted, it has the IDisposable, but it doesn't have the Dispose() method implementation, so I assume it's missing something.

Object contains no definition for"name",

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

 2
Author: Thiago Lunardi, 2017-07-19 12:16:57