EF批量添加

时间:2023-03-08 22:07:10

  1.首先,打开工具——NuGet包管理器——管理解决方案的NoGet程序包——搜索Z.EntityFramework.Extensions

EF批量添加  

  点击安装!!!

  

  codefirst定义一个实体,用EF的方法添加数据

  static void Main(string[] args)
{
using (ConsoleDBContext context = new ConsoleDBContext())
{
// '''定义要添加数据的条数'''
int customerCount = ; // '''定义一个实体集合'''
List<Users> customers = new List<Users>(); var sw = new Stopwatch();
sw.Start();
// '''想集合中添加数据'''
for (int i = ; i < customerCount; i++)
{
Users customer = new Users()
{
id = Guid.NewGuid(),
name = i + "个"
};
//customers.Add(customer);
context.Users.Add(customer);
}
context.SaveChanges(); //context.BulkInsert(customers);
//context.BulkSaveChanges();
sw.Stop();
Console.Write(sw.Elapsed);
Console.ReadKey();
} }

运行完成:插入10000条数据,用时55秒

EF批量添加

接下来我们看看用EF的拓展方法能用多长时间

  static void Main(string[] args)
{
using (ConsoleDBContext context = new ConsoleDBContext())
{
// '''定义要添加数据的条数'''
int customerCount = ; // '''定义一个实体集合'''
List<Users> customers = new List<Users>(); var sw = new Stopwatch();
sw.Start();
// '''想集合中添加数据'''
for (int i = ; i < customerCount; i++)
{
Users customer = new Users()
{
id = Guid.NewGuid(),
name = i + "个"
};
customers.Add(customer);
//context.Users.Add(customer);
}
//context.SaveChanges();
context.BulkInsert(customers);
context.BulkSaveChanges();
sw.Stop();
Console.Write(sw.Elapsed);
Console.ReadKey();
}
}

运行完成:插入10000条数据,用时到0.2秒

EF批量添加

为什么扩展方法用的时间这么少?

EF自带的方法,会增加与数据库的交互次数,一般地,EF的一个上下文在提交时会打开一个数据连接,然后把转换成的SQL语句一条一条的发到数据库端,然后去提交,下面的图片是我用SQL Server Profiler记录的和数据库交互的操作,这只是一小部分,试想,如果你的数据量达到万级别(更不用说百万,千万数据了),那对数据库的压力是很大的

EF批量添加

而扩展方法运行时与数据库的交互是这样的:

EF批量添加

批量添加的方法是生成一条SQL语句,和数据库只交互一次。那为什么图片中有多条Insert语句呢,当你使用BulkInsert时,如果数据达到4万之前,那在SQL的解释时,也是很有压力的,有多情况下会超时,当然这与你的数据库服务器有关,但为了性能与安全,将Bulk操作变为分批提交,即将上W的数据进行分解,分用1W数据量提交一次,这样,对数据库的压力就小一些。

不过这种方法好像不能进行多表操作(有主外键的),如果有朋友研究好了,可以给我留言 sun645430@163.com

下面的分析引用风枫疯的文章,在这里注明:https://www.cnblogs.com/xuyufeng/p/6612589.html