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

前端 未结 9 2132
伪装坚强ぢ
伪装坚强ぢ 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:17

    Met the same problem today.

    Here is how I figured out the issue.

    I had added the identity seed to the column initially but after that I removed it. So I did not realize that when modifying the column definition in the Code first, the Id

    Property(x => x.Id)
        .HasColumnName("Id")
        .HasColumnType("int")
        .IsRequired();
    

    So Entity framework figured out that it was an Identity column and I got the exception above.

    To fix this, I added the following:

    HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
    

    so the final piece was something like:

    Property(x => x.Id)
        .HasColumnName("Id")
        .HasColumnType("int")
        .IsRequired()
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    

提交回复
热议问题