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

前端 未结 22 1161
我在风中等你
我在风中等你 2020-11-22 13:56

I have the below error when I execute the following script. What is the error about, and how it can be resolved?

Insert table(OperationID,OpDescription,Filte         


        
相关标签:
22条回答
  • 2020-11-22 14:35

    In my CASE I was inserting more character than defined in table.

    In My Table column was defined with nvarchar(3) and I was passing more than 3 characters and same ERROR message was coming .

    Its not answer but may be in some case problem is similar

    0 讨论(0)
  • 2020-11-22 14:37

    you can simply use This statement for example if your table name is School. Before insertion make sure identity_insert is set to ON and after insert query turn identity_insert OFF

    SET IDENTITY_INSERT School ON
    /*
      insert query
      enter code here
    */
    SET IDENTITY_INSERT School OFF
    
    0 讨论(0)
  • 2020-11-22 14:37

    If you are using liquibase to update your SQL Server, you are likely trying to insert a record key into an autoIncrement field. By removing the column from the insert, your script should run.

    <changeSet id="CREATE_GROUP_TABLE" >
        <createTable tableName="GROUP_D">
            <column name="GROUP_ID" type="INTEGER" autoIncrement="true">
                <constraints primaryKey="true"/>
            </column>
        </createTable>
    </changeSet>
    
    <changeSet id="INSERT_UNKNOWN_GROUP" >
        <insert tableName="GROUP_D">    
    
            <column name="GROUP_ID" valueNumeric="-1"/>
     ...
        </insert>
    </changeSet>
    
    0 讨论(0)
  • 2020-11-22 14:37

    If you're having this issue while using an sql-server with the sequelize-typescript npm make sure to add @AutoIncrement to ID column:

      @PrimaryKey
      @AutoIncrement
      @Column
      id!: number;
    
    0 讨论(0)
  • 2020-11-22 14:38

    everyone comment about SQL, but what hapend in EntityFramework? I spent reading the whole post and no one solved EF. So after a few days a found solution: EF Core in the context to create the model there is an instruction like this: modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.Id).ValueGeneratedNever();

    this produces the error too, solution: you have to change by ValueGeneratedOnAdd() and its works!

    0 讨论(0)
  • 2020-11-22 14:39

    The best solution is to use annotation GeneratedValue(strategy = ...), i.e.

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column ...
    private int OperationID;
    

    it says, that this column is generated by database using IDENTITY strategy and you don't need to take care of - database will do it.

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