本文介绍了LINQ中有DuplicateKeyException,但已设置自动递增和自动同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C#代码中出现DuplicateKeyException错误.

I'm getting a DuplicateKeyException error in my C# code.

我在dbml中将自动生成"设置为true,将自动同步"设置为OnInsert.我什至都没有触及任何手动编写的代码中的PK字段(如下所示[我的主键字段实际上称为PK]).

I've set Auto Generated = true, and Auto-Sync = OnInsert in my dbml. I'm not even touching the PK field in any manually written code (as seen below [My primary key field is actually called PK]).

using (DeviceExerciseDataDataContext context = new DeviceExerciseDataDataContext())
                {
 foreach(Data tgudData in data.Data)
                {
                    tgd = new tableData();
                    tgd.FK = key;
                    tgd.Time = tgudData.TimeStamp;
                    tgd.Calories = Convert.ToInt32(tgudData.Calories);
                    tgd.HeartRate = tgudData.AvgHr;
                    tgd.BenchAngle = tgudData.Angle;
                    tgd.WorkoutTarget = 0;
                    tgd.Reps = tgudData.Reps;
                    context.tableDatas.InsertOnSubmit(tgd);
                }
                context.SubmitChanges();
}

这是设计器中列的代码(列分别称为PK和FK)

This is the code for the column in the designer (columns are named PK and FK)

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PK", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL", IsPrimaryKey=true, IsDbGenerated=true)]
        public int PK
        {
            get
            {
                return this._PK;
            }
            set
            {
                if ((this._PK != value))
                {
                    this.OnPKChanging(value);
                    this.SendPropertyChanging();
                    this._PK = value;
                    this.SendPropertyChanged("PK");
                    this.OnPKChanged();
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FK", DbType="Int")]
        public System.Nullable<int> FK
        {
            get
            {
                return this._FK;
            }
            set
            {
                if ((this._FK != value))
                {
                    this.OnFKChanging(value);
                    this.SendPropertyChanging();
                    this._FK = value;
                    this.SendPropertyChanged("FK");
                    this.OnFKChanged();
                }
            }
        }

推荐答案

查看自动生成的代码,您可以尝试将设计器中的服务器数据类型更改为 Int NOT NULL IDENTITY .我不怀疑这会解决它,但你永远不会知道.

Looking at your auto-generated code, you may try changing the server data type in the designer to Int NOT NULL IDENTITY. I don't suspect this is going to fix it but you never know.

这篇关于LINQ中有DuplicateKeyException,但已设置自动递增和自动同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:17