Linq to SQL: Why am I getting IDENTITY_INSERT errors?

前端 未结 7 688
长发绾君心
长发绾君心 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:33

    Is your code setting the ID value explicitely to 0? (instead of leaving it untouched).

    Update 1: As you posted on the updated version, linq2sql is clearly passing the value to the db. Here is one I haven't had any trouble with:

    [Column(Storage="_CustomerID", AutoSync=AutoSync.Always, DbType="Int NOT NULL IDENTITY", IsDbGenerated=true)]
    public int CustomerID 
    

    I just saw another one, and it has the same exact definition of the one you are using.

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

    Update 2: Regarding updates, you are not supposed to do InsertOnSubmit for that. Just update the values and call .SubmitChanges (should be throwing an exception). On the insert it is really weird, as the property attributes you posted seems to be correct, so the Insert method linq2sql generates should be correct as well. I would try, re-adding the table on the designer again and verifying all the properties are correct.

    Note that the generated insert method should look like (with a matchingRig_Insert):

    private void InsertRig(Rig obj)
    {
        System.Nullable p1 = obj.Id;
    

    this.Rig_Insert(/* bunch of values */, ref p1); obj.Id = p1.GetValueOrDefault(); }

提交回复
热议问题