Search code examples
c#entity-frameworkctp4

Entity Framework CTP 4. "Cannot insert the value NULL into column" - Even though there is no NULL value


Im using EF CTP 4. I have a simple console app (for testing purposes) that is using EF to insert some data into a SQL database.

I have come to a problem where by upon inserting the item

using(var context = GetContext())
{
   BOB b = new BOB();
   b.Id = 1;

   context.Bobs.Add(b);
   context.SaveChanges();
}

It throws the error: {"Cannot insert the value NULL into column 'Id', table 'TestDB.dbo.BOB'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

The Table just has 1 field of Id int NOT NULL which is the primary key and is not an auto incremented Id.

On the creation of the DataContext I have this configuration, which yes does get fired.

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<BOB>().HasKey(b => b.Id);
    builder.Entity<BOB>().MapSingleType().ToTable("BOB");
}

I have also pre-populated this table and then through the debugger been able to via watch load up this BOB object... so I am really stumped, as for being able to load up my BOB shows that all is right... however upon inserting a new one it crashes...


Solution

  • Have you tried explicitly specifying the StoreGeneratedPattern?

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