Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using Parallel.ForEach benefit in ObjectContext.Add

I am using Entity Framework with the generic repository pattern. I have used the following method to add an object.

public int Add<TEntity>(TEntity entity) where TEntity : class
{
   DataContext.AddObject(GetEntityName<TEntity>(), entity);
   return SaveChanges();
}

I am also thinking of extending this to support multiple entities.

public int Add<TEntity>(TEntity[] collection) where TEntity : class
{
   foreach (TEntity item in collection)
   {
     DataContext.AddObject(GetEntityName<TEntity>(), item);
   }

   return SaveChanges();
}

Will there be an actual benefit in using Parallel.ForEach instead of the foreach loop in the above scenario?

Also because I haven't called SaveChanges() until the end of the loop, if there is lets say a primary key violation, will it be thrown inside the loop or when SaveChanges() is called? Will I be able to rollback the changes?

like image 238
Ranhiru Jude Cooray Avatar asked Feb 07 '26 15:02

Ranhiru Jude Cooray


1 Answers

ObjectContext is not thread safe. Here's the remark on MSDN

The ObjectContext class is not thread safe. The integrity of data objects in an ObjectContext cannot be ensured in multithreaded scenarios.

So better not use Parallel.ForEach.

like image 90
Eranga Avatar answered Feb 12 '26 14:02

Eranga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!