Linq to SQL: Why am I getting IDENTITY_INSERT errors?

前端 未结 7 694
长发绾君心
长发绾君心 2020-12-17 02:49

I\'m using Linq to SQL. I have a DataContext against which I am .SubmitChanges()\'ing. There is an error inserting the identity field:

Cannot insert explicit value for         


        
7条回答
  •  甜味超标
    2020-12-17 03:26

    I was having the exact same problem.

    My solution was to manually make the identity INT column into a nullable INT? column in the DBML designer, not in the actual table of the DB of course. Also set the DbType to NULL instead of NOT NULL. Like so:

    [Column(Storage="_TestID", AutoSync=AutoSync.OnInsert, DbType="Int NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] 
    public int? TestID
    

    This works with all DB operations. When inserting simply set the identity column to NULL rather than to 0.

提交回复
热议问题