我的C#代码中出现DuplicateKeyException错误。
我在我的dbml中设置了Auto Generated = true和Auto-Sync = OnInsert。我甚至没有在任何手动编写的代码中触摸PK字段(如下所示[我的主键字段实际上称为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)
[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();
}
}
}
答案 0 :(得分:2)
查看自动生成的代码,您可以尝试将设计器中的服务器数据类型更改为 Int NOT NULL IDENTITY 。我不怀疑这会解决它,但你永远不知道。