Inserting Single Quotes Null Field

3

I created a very simple application to simulate a small register of clients, but when testing the data manipulation by the application I could see in the database that the fields that are null in the register are inserted into the database with two single quotes ( '').

In other applications I can solve this by changing the data type of the parameter to NpgsqlDbType.Text , but I do not know a way to do this in EF.

I use a POCO Entity class mapped like this:

[Table("cliente", Schema = "public")]
public class Cliente
{
    [Key]
    [Column("id")]
    public int Id { get; set; }

    [Required(ErrorMessage = "Nome não pode ser nulo.")]
    [Column("nome")]
    public string Nome { get; set; }

    [Required(AllowEmptyStrings = true)]
    [Column("endereco")]
    public string Endereco { get; set; }


    [Column("bairro", TypeName="text")]
    public string Bairro { get; set; }

    [Required(ErrorMessage = "Cidade não pode ser nulo.")]
    [Column("cidade")]
    public int CidadeID { get; set; }

    [ForeignKey("CidadeID")]
    public Cidade Cidade { get; set; }

    [Column("cpfcnpj")]
    public string CPFCNPJ { get; set; }

    [Column("telefone")]
    public string Telefone { get; set; }

    [Column("ativo")]
    public bool Ativo { get; set; }

    public virtual IQueryable<Cliente> Clientes { get; set; }

}

Below method that inserts the customer data entered in the form into the database:

    public static void InserirCliente(Cliente cli)
    {
        using (var db = new Repositorio.DBContexto())
        {
            try
            {
                db.Clientes.Add(cli);
                var usuarioSalvo = db.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

Below the event method started by the Click of a Save button:

    private void btnSalvar_ItemClick(object sender, ItemClickEventArgs e)
    {

        try
        {
            var cliente = new Cliente();
            cliente.Nome = Convert.ToString(txtNome.EditValue);
            cliente.Telefone = Convert.ToString(txtTelefone.EditValue);
            cliente.CPFCNPJ = Convert.ToString(txtCPF.EditValue);

            cliente.Endereco = Convert.ToString(txtEndereco.EditValue);
            cliente.Bairro = Convert.ToString(txtBairro.EditValue);
            cliente.CidadeID = Convert.ToInt32(lkeCidade.EditValue);
            cliente.Ativo = true;

            DAL.ClienteDAL.InserirCliente(cliente);

            MessageBox.Show("Cliente Inserido com Sucesso!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.OK;
            this.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(string.Format("{0}\n\n{1}", ex.Message, ex.InnerException), "Ooops", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

Is there any way to prevent "single quotes" from being entered in fields that allow null values?

    
asked by anonymous 28.04.2016 / 23:04

2 answers

2

To stay in response to what I had already commented:

The problem is that the data in the application is empty string and not null. It then writes an empty string . If you want to write a null in the database you need to ensure that the data is null.

If the data is already null, just do this:

cliente.Nome = txtNome.EditValue;

I do not see why doing a string conversion of something that is already string . Converting a null to string gives a void and not a null value object, as demonstrated by documentation . The error is there, so the other fields work.

If there is any chance of not having a valid number in the integer value field below, there will be an unnecessary exception (ie programming error):

 Convert.ToInt32(lkeCidade.EditValue)

Also, you should never catch an exception just to relaunch it. This only causes problems. If you have nothing useful to do when catching an exception, do not capture it.

Capturing Exception is also not usually appropriate in most situations. Just like trying to close some things without a standard that guarantees that this will be closed. The current code can easily leak features open.

    
29.04.2016 / 00:11
0

Solution Found !!!

Thanks to the comment from colleague BIGOWN I was making sure that the value of the field was null ... I added a validation in the conversion of the values to the Client object and bingo !!! The problem has been solved !!

I basically added this validation to passing values.

 cliente.Bairro = (txtBairro.EditValue == null ? null : Convert.ToString(txtBairro.EditValue));

Thank you so much !!

    
28.04.2016 / 23:39