0

I've to process 1000+ xml files and insert to database tables using EF code first. I'm using Guid as primary key for each table.

Xml file deserialize to One main table and dependent tables (like MyDepTable1, MyDepTable2, MyDepTable3). I am just using below.

       dbContext.MyMainTable.Add(myObject);
       dbContext.SaveChanges(); 

Everything works fine if I am using for each loop. All main and dependentables records are inserted.

Once I start using Parallel.ForEach I am getting an exception saying Violation of PRIMARY KEY constraint 'PK_MyDepTable1'. Cannot insert duplicate key in object 'dbo.MyDepTable1'. The duplicate key value is (066c73ce-2dc7-4702-5b0a-08d9ec6f7750).

I've tried using NEWSEQUENTIALID() as Default in SQL, I've tried using Guid.NewGuid() from C#, everything fails when used with Parallel.

Any help is greatly appreciated.

I've referred to stackoverflow articles with similar problems but couldn't find any solution.

  • 1
    Related questions: [Is DbContext thread safe?](https://stackoverflow.com/questions/6126616/is-dbcontext-thread-safe) and [Is a DbContext per thread in Parallel.ForEach safe?](https://stackoverflow.com/questions/57796444/is-a-dbcontext-per-thread-in-parallel-foreach-safe) – Theodor Zoulias Feb 10 '22 at 09:15
  • Why guid for primary key? Is neccesary? – Dani Feb 10 '22 at 09:24
  • @Dani Problem exists for int also..Its a different error though...Identity_Insert is off for the dependent tables for Parallel. – user6095576 Feb 10 '22 at 09:27
  • @user6095576 But... if you use an incremental int pk, error persists? – Dani Feb 10 '22 at 09:28
  • I've tried DatabaseGenerated(DatabaseGeneratedOption.Identity) for Integer. – user6095576 Feb 10 '22 at 09:30
  • If you have an autoincremental id you don't have to use any method, just don't assign a value to it and the database will take care of it in .Add – Dani Feb 10 '22 at 09:31
  • Yes, that's what I did still error with Identity_Insert is off for the dependent tables for Parallel. – user6095576 Feb 10 '22 at 10:58
  • Wait... you are talking about dependent tables but code only shows 1 table... post full code please... – Dani Feb 10 '22 at 19:00

0 Answers0