LINQ won't insert all records in que (possible overwriting of records?)
here's my following code (that used to work). It's supposed to add multiple records (I guess objects in LINQ case) to the context object, then submit to the DB. Issue is, only one record is making it to the DB now, when several used to get inserted.
using (DeviceExerciseDataDataContext context = new DeviceExerciseDataDataContext())
{
foreach(UpdateData tgudData in data.UpdateData)
{
tgd.FK = 1;
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.Datas.InsertOnSubmit(tgd);
}
context.SubmitChanges();
}
Now, I tried putting the context.SubmitChanges()
into the foreach block, and this is the error it gave.
Cannot insert explicit value for identity column in table 'tablename' when IDENTITY_INSERT is se开发者_StackOverflow中文版t to OFF.
Mind you, I'm not inserting into the primary key column, and the PK column is set to auto increment, and is identity.
Any ideas for me, as to why my code isn't inserting multiple records anymore?
You only use a single class instance for tgd
, hence only one record is created - you are just overwriting the properties of the existing tgd
instance repeatedly. Instead you have to new up tgd
inside the loop, i.e:
foreach(UpdateData tgudData in data.UpdateData)
{
tgd = new WhateverTgdIs();
tgd.FK = 1;
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.Datas.InsertOnSubmit(tgd);
}
精彩评论