In savechages it says which column is null and has value

Asked

Viewed 31 times

0

When I call my method to record, the whole object comes filled in, but when savechanges() is called it says that Idbalanca is null and yet it has the value of 1. Method Insert:

public virtual void Inserir(T item) 
        {
            contexto.Set<T>().Add(item);
            contexto.SaveChanges();
        }

The Item object is filled in. See below for an image on top of the object before saving(savechanges) inserir a descrição da imagem aqui

  • The only way I could, was to create an Identity field. Without it, I got nothing.

  • You want to explicitly pass the Idbalanca value instead of letting the database generate with auto-increment?

  • @Alisson, yes, because it’s in the client, but we’ll figure it out and I think Entity can do it, right? Because otherwise Entity is flawed in this sense, to work with fields not automatically generated

1 answer

1

The Entity Framework by default treats primary keys as Identity, so it will ignore any value you set for IdBalanca, once it is the key. At the same time, because it is Identity, the Entity Framework believeth that your table will have an automatically generated value (eg auto-increment).

So it gives this error, it ignores what was filled in the code, and does not define a value when entering in the table, but as the table at the same time is not Identity, this error occurs.

To tell the Entity Framework that the value is not generated by the database, but by the application itself, you need to configure the field with the attribute DatabaseGenerated:

public class Balanca
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdBalanca { get; set; }

    // demais campos...

}
  • Thanks. I’ll test and see if it works.

Browser other questions tagged

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