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?
ObjectContext is not thread safe. Here’s the remark on MSDN
So better not use
Parallel.ForEach.