Entity Framework error: Cannot insert explicit value for identity column in table

前端 未结 8 1867
孤城傲影
孤城傲影 2020-11-27 07:09

I\'m getting this error on EF.

Cannot insert explicit value for identity column in table \'GroupMembers_New\' when IDENTITY_INSERT is set to OFF.

相关标签:
8条回答
  • 2020-11-27 07:27

    In EF 6, there is a property of the field/column in your model for doing this: StoreGeneratedPattern.

    Set this to "Identity" in the property dropdown list.

    (I don't know about EF 4. The above answer, using IsDbGenerated, seems to be for EF 4.)

    And this corresponds in the underlying XML to an attribute to the element:

    <Property Name="MyTableId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
    

    --but you don't need to deal with the XML manually, since you can use the designer.

    How this gets messed up isn't clear. I had the problem even after refreshing my model from the database. Perhaps it gets confused if you set the PK on the table, or change its name, after you have already generated the model. (I am using the table/database-first approach, not code first.)

    You can't use the above approach of putting the C# attribute on the entity code, because in this situation the entity code is generated by EF. EF is supposed to understand ("by itself") that the field is an identity.

    0 讨论(0)
  • 2020-11-27 07:28

    Try this:

    using System.ComponentModel.DataAnnotations.Schema;
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public decimal Identity_Col { get; set; }
    

    The Entity Framework class file adds these lines of code to the Identity column.

    0 讨论(0)
提交回复
热议问题