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

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

    Simply delete the tables that are dragged into your .dbml file and re-drag them again. Then Clean solution>Rebuild solution> Build solution.

    Thats what worked for me.

    I didnt made the table on my own, I was using VS and SSMS, I followed this link for ASP.NET Identity:https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

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

    Be very wary of setting IDENTITY_INSERT to ON. This is a poor practice unless the database is in maintenance mode and set to single user. This affects not only your insert, but those of anyone else trying to access the table.

    Why are you trying to put a value into an identity field?

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

    In your entity for that table, add the DatabaseGenerated attribute above the column for which identity insert is set:

    Example:

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TaskId { get; set; }
    
    0 讨论(0)
  • 2020-11-22 14:29

    Another situation is to check that the Primary Key is the same name as with your classes where the only difference is that your primary key has an 'ID' appended to it or to specify [Key] on primary keys that are not related to how the class is named.

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

    Note that if you are closing each line with ;, the SET IDENTITY_INSERT mytable ON command will not hold for the following lines.

    i.e.
    a query like

    SET IDENTITY_INSERT mytable ON;
    INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole');
    

    Gives the error
    Cannot insert explicit value for identity column in table 'mytable' when IDENTITY_INSERT is set to OFF.

    But a query like this will work:

    SET IDENTITY_INSERT mytable ON
    INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole')
    SET IDENTITY_INSERT mytable OFF;
    

    It seems like the SET IDENTITY_INSERT command only holds for a transaction, and the ; will signify the end of a transaction.

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

    don't put value to OperationID because it will be automatically generated. try this:

    Insert table(OpDescription,FilterID) values ('Hierachy Update',1)
    
    0 讨论(0)
提交回复
热议问题