Can’t find Parameter passed to the Insert command

Asked

Viewed 165 times

2

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

Client does not contain 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

Projeto

2 answers

3


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 in the Github for future reference.

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

I cleaned up good, taking away unnecessary things like the IDisposable, Exception capture that does nothing, but could have better other things. I eliminated the partial class that 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. Why use _codigo, if codigo is enough. This is not usually indicated as nomenclature in C#. Because the property Codigo is capitalized, and should be so, and email is in lower case? Be consistent.

2

There are many "opportunities for improvement" in your code.

Partial Classe

What’s in the ClientDAO? Why did you create a class partial Cliente? What motivation? If you were an abstract, because you might 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’s no use doing that:

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 if you give exception, this will do the Bubble up natively.

Repositorio - DAO

Do not mix responsibility. Your entity Cliente must 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 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();
        }            
    } 
}

Misuse of Idisposable

Idisposable is used 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, you have Idisposable, but you don’t have the method implementation Dispose(), then I assume something is missing.

Object does not contain 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 - very likely a typo.

Browser other questions tagged

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