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

后端 未结 2 1894
慢半拍i
慢半拍i 2020-12-11 10:45

I\'m using code first with entity framework. I have been getting the error below and can\'t figure out how to fix it:

\"Cannot insert explicit value for identity col

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 10:59

    You have to first turn it ON, then do your insert and then turn it OFF

    Sql("SET IDENTITY_INSERT Genres ON");
    
    Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
    Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
    Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
    Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
    Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
    
    Sql("SET IDENTITY_INSERT Genres OFF");
    

    But, the point of having an identity column is that we don't choose what values the identity holds (read up on surrogate keys). In that case, you just remove the ID column from your insert

    Sql("INSERT INTO Genres (Name) VALUES ('Action')");
    Sql("INSERT INTO Genres (Name) VALUES ('Thriller')");
    Sql("INSERT INTO Genres (Name) VALUES ('Family')");
    Sql("INSERT INTO Genres (Name) VALUES ('Romance')");
    Sql("INSERT INTO Genres (Name) VALUES ('Comedy')");
    

提交回复
热议问题