EF批量插入資料耗時對比
阿新 • • 發佈:2018-12-01
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF批量插入 { class Program { static void Main(string[] args) { TestEntities test = new TestEntities(); DateTime time1 = DateTime.Now;for (int i = 0; i < 10000; i++) { User user = new User(); user.Name = "測試" + i.ToString(); test.User.Add(user); test.SaveChanges(); } DateTime time2 = DateTime.Now; TimeSpan ts = new TimeSpan(time1.Ticks); TimeSpan ts2= new TimeSpan(time2.Ticks); Console.WriteLine("不批量插入:"+( ts2-ts)); //引入Z.EntityFramework.Extensions 批量插入 DateTime time3 = DateTime.Now; List<User> list = new List<User>(); for (int i = 0; i < 10000; i++) { User user= new User(); user.Name = "測試" + i.ToString(); list.Add(user); } test.BulkInsert(list); test.SaveChanges(); DateTime time4 = DateTime.Now; TimeSpan ts3 = new TimeSpan(time3.Ticks); TimeSpan ts4 = new TimeSpan(time4.Ticks); Console.WriteLine("批量插入"+(ts4 - ts3)); Console.ReadKey(); } } }
最終結果: 單個插入用時90秒。 批量插入不到3秒