In savechages says column is null and has value

0

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

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

The Item object is fully populated. See below an image on top of the object before recording (savechanges)

    
asked by anonymous 17.08.2017 / 17:02

1 answer

1
The Entity Framework defaults to the primary keys as Identity , so it will ignore any value you set to IdBalanca , once it is the key. At the same time, for being Identity, the Entity Framework believes that your table will have an automatically generated value (eg auto-increment).

So it gives this error, it ignores what was populated in the code, and does not define a value when inserting into the table, but since 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 DatabaseGenerated :

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

    // demais campos...

}
    
17.08.2017 / 19:28