/// <summary> /// Uses a reliable connection retry policy and transaction /// scoping to add and submit a set of EntityObjects. Submits items /// a page at a time. /// </summary> /// <typeparam name="T">Must derive from <typeparamref name="EntityObject"/>.</typeparam> /// <param name="context">Any ObjectContext</param> /// <param name="objects">A set of <typeparamref name="EntityObject"/>s to save.</param> /// <param name="pageSize">The number of items to submit at one time.</param> public static void AddObjectsAndSave <T>( this ObjectContext context, IEnumerable <T> objects, int pageSize = 1000, Action <IEnumerable <T> > doThisInstead = null) where T : EntityObject { if (!objects.Any()) { return; } var name = context.GetTableName <T>(); var watch = new Stopwatch(); var times = new List <TimeSpan>(); int page = 1; PaginatedList <T> items = null; var hasNextPage = true; while (hasNextPage) { //reset watch watch.Reset(); watch.Start(); //get page of items and save them items = new PaginatedList <T>(objects.AsQueryable(), page, pageSize); hasNextPage = items.HasNextPage; if (doThisInstead != null) { doThisInstead(items); } else { context.AddObjectsAndSave(items); } page++; //record time watch.Stop(); times.Add(watch.Elapsed); Console.Write("{0}: {1} rows in {2}.", name, items.Count, watch.Elapsed.ToPrettyString()); Console.WriteLine(" Page {0}/{1}, {2} complete, ETA: {3}.", items.PageNumber, items.TotalPages, ((double)items.PageNumber / (double)items.TotalPages).ToString("P"), DateTime.Now.AddSeconds( times.Average((ts) => ts.TotalSeconds) * (items.TotalPages - page)).ToLongTimeString()); } Console.WriteLine("{0} done! Took {1}.", name, TimeSpan.FromSeconds(times.Sum((ts) => ts.TotalSeconds)).ToPrettyString()); }
public static void AddObjectsAndSaveWithIdentityInsert <T>( this ObjectContext context, IEnumerable <T> objects) where T : EntityObject { if (!objects.Any()) { return; } Action <IEnumerable <T> > exec = (obj) => { var policy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy> (10, TimeSpan.FromSeconds(10)); var name = context.GetTableName <T>(); foreach (var item in obj) { context.AddObject(name, item); } policy.ExecuteAction(() => { context.Connection.Open(); var trans = context.Connection.BeginTransaction(); context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " ON"); context.SaveChanges(); context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " OFF"); trans.Commit(); context.AcceptAllChanges(); context.Connection.Close(); }); }; context.AddObjectsAndSave(objects, doThisInstead: exec); }