"; column does not allow zeros. INSERT will not work EF 6.1 So, I'm try...">

Cannot insert a NULL value in the column "MaintenanceId", table "<tableName>"; column does not allow zeros. INSERT will not work EF 6.1

So, I'm trying to make it simple to add a record to my db on azure, but for some reason db does not generate PK for writing.
Below is the code used to create db and write. This is on EF 6.1 on a console application.

Context

public BlizzardDbContext() : base("AzureSqlDb") { } public DbSet<Maintenance> Maintenances { get; set; } 

Model

 public class Maintenance { public Maintenance() {} public Maintenance(DateTime start, DateTime end, string info) { Start = start; End = end; Info = info; } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int MaintenanceId { get; set; } public DateTime? Start { get; set; } public DateTime? End { get; set; } public string Info { get; set; } } 

Failed to save while saving changes

 var context = new BlizzardDbContext(); context.Maintenances.Add(new Maintenance() {Start = DateTime.Now, End = DateTime.Now, Info = ""}); context.SaveChanges(); 

I know that it sounds so simple, I used EF several times before, but I canโ€™t understand what is happening this time and here is the error

"Cannot insert a NULL value in the column" MaintenanceId ", the table" .dbo.Maintenances ", the column does not allow zeros. INSERT does not work. \ R \ nThe application has completed.

enter image description here

Update: finished, fixing it, deleting db and re-creating it, I think that there was something strange with EF, it did not update db with the correct migration, since after reconstructing its column, then Identity was set

+7
c # sql-server entity-framework azure
source share
2 answers

Just check if MaintenanceId is a private key or not in the database. If this is not the case, or you are not sure you can try the options below.

change

  [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 

to

 [DatabaseGenerated(DatabaseGeneratedOption.None)] 

.None - this means: "The database does not generate values."

+2
source share

Log into your database and verify that MaintenanceId does indeed automatically generate the key. EF supports this , and I suspect that something funny happened during the migration if you used it or while building the table.

Also, make sure that you have not disabled object tracking in your DbContext class. It is enabled by default, so if you havenโ€™t explicitly disabled it, you donโ€™t need to worry about it :)

0
source share

All Articles