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

前端 未结 8 1872
孤城傲影
孤城傲影 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:

    
    

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

提交回复
热议问题