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

前端 未结 22 1163
我在风中等你
我在风中等你 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:41

    Simply If you getting this error on SQL server then run this query-

    SET IDENTITY_INSERT tableName ON
    

    This is working only for a single table of database e.g If the table name is student then query look like this:

    SET IDENTITY_INSERT student ON
    

    If you getting this error on your web application or you using entity framework then first run this query on SQL server and Update your entity model (.edmx file) and build your project and this error will be resolved

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

    And if you are using Oracle SQL Developer to connect, remember to add /sqldev:stmt/

    /sqldev:stmt/ set identity_insert TABLE on;

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

    In my case I was having set another property as key in context for my modelBuilder.

    modelBuilder.Entity<MyTable>().HasKey(t => t.OtherProp);
    

    I had to set the proper id

     modelBuilder.Entity<MyTable>().HasKey(t => t.Id);
    
    0 讨论(0)
  • 2020-11-22 14:44

    I solved this problem by creating a new object every time I want to add anything to the database.

    0 讨论(0)
  • 2020-11-22 14:45
    1. This occurs when you have a (Primary key) column that is not set to Is Identity to true in SQL and you don't pass explicit value thereof during insert. It will take the first row, then you wont be able to insert the second row, the error will pop up. This can be corrected by adding this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in your PrimaryKey column and make sure its set to a data type int. If the column is the primary key and is set to IsIDentity to true in SQL there is no need for this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    2. this also occurs when u have a column that is not the primary key, in SQL that is set to Is Identity to true, and in your EF you did not add this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    0 讨论(0)
  • 2020-11-22 14:47

    I'm not sure what the use for the "Insert Table" is, but if you're just trying to insert some values try:

    Insert Into [tablename] (OpDescription,FilterID)
    values ('Hierachy Update',1);
    

    I had the same error message come up, but I think this should work. The ID should auto-increment automatically as long as it's a primary key.

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