Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot insert the value NULL into column 'MaintenanceId', table '<tableName>'; column does not allow nulls. INSERT fails EF 6.1

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."

enter image description here

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

like image 710
Toxicable Avatar asked Mar 30 '16 04:03

Toxicable


1 Answers

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."

like image 115
Shrutika Kalra Avatar answered Nov 03 '22 02:11

Shrutika Kalra