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

前端 未结 9 2133
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 00:43

I am writing my project using Entity Framework 4.0 (Model first). At the beginning of the project, I faced with this problem: I am trying to insert the filled object in the

9条回答
  •  难免孤独
    2020-12-10 01:12

    I know I'm a bit late but here's how I managed to fix it.

    1. I included these attributes to my int PK in my models. (to give way for my seed in configuration.cs) [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]

    2. After I've inserted my seed I use the SQL Server Object Explorer in Visual Studio and went to the table of this model by right clicking the table and press 'View Designer'

    3. Below you will see the script generated for creating that table. Insert this command right after your primary key property.

      IDENTITY(1,1)

    1. Apply script changes by clicking 'Update' just above the table view (left corner)

    2. After updating the database, go back to your model and change this attribute:

      [DatabaseGenerated(DatabaseGeneratedOption.None)] to [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    3. Save, Add migration then Update Database should do it.

    Everytime you insert, it will now increment depending on what you specified on the IDENTITY script.

提交回复
热议问题