Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code first - Cannot insert the value NULL into column 'Id'

This is my code, very simple...

 var newUser = new User();
        newUser.Id=id;
        newUser.Email = email;
       this.DataContext.Set<User>().Add(newUser);
        this.DataContext.SaveChanges();

The error I get is a sqlexception at this.DataContext.SaveChanges(); stating that:

Cannot insert the value NULL into column 'Id', table 'xxxxx.dbo.Users'; column does not allow nulls. INSERT fails.

I have debugged and found that there is value in Id & Email in newUser at this.DataContext.Set<User>().Add(newUser);

If this is the case, how is the value becoming null?

The error stack trace:

[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
   System.Data.Entity.Internal.InternalContext.SaveChanges() +204
   System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +23
   System.Data.Entity.DbContext.SaveChanges() +20

I have not been able to understand or solve this....

Would sincerely appreciate any help in this...

Regards Arnab

Solution

Ok, thanks to Ladislav to point me in the right direction: Adding the attribute [DatabaseGenerated(DatabaseGeneratedOption.None)] solved the problem.

like image 779
Arnab Avatar asked Oct 22 '11 07:10

Arnab


2 Answers

Referring to this post it seems that entity framework expects by default that you insert into identity column.

To solve this try:

modelBuilder.Entity<BOB>()
    .HasKey(p => p.Id)
    .Property(p => p.Id)
    .StoreGeneratedPattern = StoreGeneratedPattern.None;

builder.Entity<BOB>().MapSingleType().ToTable("BOB");

or decorate your key in the POCO with:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)] //Fixed typo
public Int64 PolicyID { get; set; }
like image 62
Ahmed Eid Yamany Avatar answered Nov 13 '22 09:11

Ahmed Eid Yamany


I ran into the same problem, found your question, and then noticed this Entity Framework 4.1 code-first KeyAttribute as non-identity column question ( which has an attribute that solved my problem ).

If you define User as:

public class User
{
    [DataMember, Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ID { get; set; }

    [DataMember]
    public string Email { get; set; }
}

The key here is putting the attributes:

  • Key
  • DatabaseGenerated

onto the ID column. Apparently the issue we are fighting is that Entity Framework by default expects to do inserts with keys being identities.

like image 7
badMonkey Avatar answered Nov 13 '22 07:11

badMonkey