Why is EF trying to insert NULL in id-column?

Try to add this into your model class .cs file:

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CategoryId { get; set; }

Or change your column CategoryId to identity:

    CategoryId int IDENTITY(1,1)

Have a look at this: https://stackoverflow.com/a/5338384/171703 - entity framework might be assuming that your CategoryId field is an identity and therefore passing null to the database expecting it to fill it for you.


I ran into this today and had to regenerate my EF classes from the database.

After doing that, I found that EF added:

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

to this"Id" field that used to be an Identity column in the SQL but was changed to be app-assigned.

I think if you don't have that attribute EF won't actually send the ID to the database ('convention over configuration')


I had created the table with int Id as PK, but had forgotten to set "Identity Specification" = True