Fastest Way of Inserting in Entity Framework

前端 未结 30 2181
鱼传尺愫
鱼传尺愫 2020-11-21 05:23

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

30条回答
  •  忘了有多久
    2020-11-21 05:53

    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();
        }
    }
    

提交回复
热议问题