1

I am trying to do an update on a record in my database using linq2sql, however, I am getting the following exception thrown:

 'System.Data.Linq.DuplicateKeyException' in System.Data.Linq.dll ("Cannot add an entity with a key that is already in use.")   System.Data.Linq.DuplicateKeyException

Although I understand what the exception is telling me, how is this possible when doing an update? I am not inserting any data so realistically no keys should be updated?

 var Printer = db.Printers.FirstOrDefault(p => p.id == i.PrinterId);
 Printer.CenterId = GetCenterId(i.NewCenterCode);
 Printer.LastCenterCode = i.NewCenterCode;
 db.SubmitChanges();

Any ideas?

mauzilla
  • 3,574
  • 10
  • 50
  • 86
  • Does `CenterId` have a unique constraint ? Do you do any operations with your `db` context before the piece of code that you've shown ? – Zein Makki Aug 30 '16 at 06:14
  • @user3185569 or `LastCenterCode` for that matter – Keyur PATEL Aug 30 '16 at 06:18
  • Neither of them have a unique constraint, the only 2 unique columns are ID (primary key) and MacAddress (which in this case is not being updated) – mauzilla Aug 30 '16 at 06:23

1 Answers1

0

It is possible that you are using your dbcontext 'too much' and that the dbcontext is already managing the same record you are trying to update.

Try using a new dbcontext to perform the update. Dbcontexts are meant to be created used and disposed frequently.

https://stackoverflow.com/a/3151724/711061

Community
  • 1
  • 1
Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50
  • This very well may be the case, my app filters a CSV with around 60k records and I am creating a single dbcontext per class. I am running a large number of loops so is it best to create a new context within each loop? – mauzilla Aug 30 '16 at 08:01
  • Well.. no. A dbcontext should be used locally to perform as much atomic work as possible. You decide what's atomic and minimal. I'd use a single dbcontext for the loop, and maybe for the entire update method. – Mauro Sampietro Aug 30 '16 at 08:06