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

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

    I had this issue in my app; and got fixed it changing the property "StoredGeneratedPattern" of the id field to Identity.

    So, Go to the model; look up for the table; click on propierties of the primary key fiel; and change the property.

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

    First match in google, so here is my solution:

    EF Code first: Because of an auto-increment PK 'id' field AND a guid column, design like this:

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid FileToken { get; set; }
    

    there was a duplicate identity. I changed it to:

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    [DefaultValue("newid()")]
    public Guid FileToken { get; set; }
    

    and the problem went away.

    Hope it helps you.

    Erik

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

    I have run into this before. This error means you are trying to assign a value explicitly to a column where the database automatically assigns it.

    Suggestion: Update your edmx file to reflect any changes you may have made in the database. If the database automatically assigns the value, you should see the "IsDbGenerated=true" attribute in your designer file under that property. If it's not there, you can add it manually.

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

    I encountered the same problem and error message in my AspNetCore 2.x application. The only way I could solve it was by removing this line in the ModelBuilder.Entity method of the DbContext class:

    // remove: entity.Property(e => e.Id).ValueGeneratedNever();
    
    0 讨论(0)
  • 2020-11-27 07:15

    See intercepting Entity Insert for generated always columns like StartTime and EndTime columns on history tables, rowversion columns as well.

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

    Put these attribs on top of the property which is identity:

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    
    0 讨论(0)
提交回复
热议问题