EF 批量添加数据
原文:https://www.cnblogs.com/liuruitao/p/10049191.html
原文:https://www.cnblogs.com/yaopengfei/p/7751545.html
环境:
就只安装了两个包,除此之外无其它任何配置,
EntityFramework、Z.EntityFramework.Extensions
一个简单的测试:
using System; using System.Collections.Generic; using System.Data.Entity; namespace ConsoleApp2 { class Program { static void Main(string[] args) { using (var db = new BlogEntities()) { //添加一条数据 //Blog entity = new Blog(); //entity.BlogId = 1; //entity.Title = "title1"; //entity.CreateDate = DateTime.Now; //db.Blogs.Add(entity); //db.SaveChanges(); //查看 添加的数据 和 数据库链接地址 //int i = db.Blogs.ToList().Count; //var d = db.Blogs.FirstOrDefault(); //var str = db.Database.Connection.ConnectionString; int total = 1000; //测试1 DateTime dt1 = DateTime.Now; for (int i = 0; i < total; i++) { Blog entity = new Blog(); entity.BlogId = 1; entity.Title = "title" + i.ToString(); entity.CreateDate = DateTime.Now; db.Blogs.Add(entity); db.SaveChanges(); } Console.WriteLine("不批量插入1:" + (DateTime.Now - dt1).TotalMilliseconds); //测试2 和测试1的区别 在于 db.SaveChanges(); 的位置 DateTime dt2 = DateTime.Now; for (int i = 0; i < total; i++) { Blog entity = new Blog(); entity.BlogId = 1; entity.Title = "title" + i.ToString(); entity.CreateDate = DateTime.Now; db.Blogs.Add(entity); } db.SaveChanges(); Console.WriteLine("不批量插入2:" + (DateTime.Now - dt2).TotalMilliseconds); //测试3 需要引入Z.EntityFramework.Extensions 批量插入 DateTime dt3 = DateTime.Now; List<Blog> list = new List<Blog>(); for (int i = 0; i < total; i++) { Blog entity = new Blog(); entity.BlogId = 1; entity.Title = "title" + i.ToString(); entity.CreateDate = DateTime.Now; list.Add(entity); } db.BulkInsert(list); db.SaveChanges(); Console.WriteLine("批量插入:" + (DateTime.Now - dt3).TotalMilliseconds); Console.ReadKey(); } } } public class Blog { public int BlogId { get; set; } public string Title { get; set; } public DateTime CreateDate { get; set; } } public class BlogEntities : DbContext { public DbSet<Blog> Blogs { get; set; } } }