So i'm trying to do a simple add an entry to my db on azure but for some reason the db is not generating my PK for the entry.
Below is all the code used to create the db and do the entry.
This is on EF 6.1 on a console app
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; }
}
Test that failed on save changes
var context = new BlizzardDbContext();
context.Maintenances.Add(new Maintenance() {Start = DateTime.Now, End = DateTime.Now, Info = ""});
context.SaveChanges();
I know it sounds so simple, i've used EF a few times before but cannot figure out what is going wrong this time and here's the error
"Cannot insert the value NULL into column 'MaintenanceId', table '.dbo.Maintenances'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."
Update: Ended up fixing this by deleting the db and recreating it, I think there was something weird going on with EF, it wasn't updating the db with the migration properly since after recreating it the column was then set to be Identity
Just verify whether the MaintenanceId is identity key or not in DB. If it is not or you are not sure you can try below option
change
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
to
[DatabaseGenerated(DatabaseGeneratedOption.None)]
.None - That means "The database does not generate values."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With