I\'m looking for the fastest way of inserting into Entity Framework.
I\'m asking this because of the scenario where you have an active TransactionScope
a
I have made an generic extension of @Slauma s example above;
public static class DataExtensions
{
public static DbContext AddToContext(this DbContext context, object entity, int count, int commitCount, bool recreateContext, Func contextCreator)
{
context.Set(typeof(T)).Add((T)entity);
if (count % commitCount == 0)
{
context.SaveChanges();
if (recreateContext)
{
context.Dispose();
context = contextCreator.Invoke();
context.Configuration.AutoDetectChangesEnabled = false;
}
}
return context;
}
}
Usage:
public void AddEntities(List entities)
{
using (var transactionScope = new TransactionScope())
{
DbContext context = new YourContext();
int count = 0;
foreach (var entity in entities)
{
++count;
context = context.AddToContext(entity, count, 100, true,
() => new YourContext());
}
context.SaveChanges();
transactionScope.Complete();
}
}