当前位置: 首页 > 编程日记 > 正文

关于EF中批量添加的个人探索

实际的测试代码和数据记录,还有最终的总结都在下面:

        /// <summary>/// 这种做法,不用了说了,每次遍历都会打开一次db链接,然后执行insert操作;/// </summary>static void CreateBluckInsertData0(){using (var context = new SiteDbContext()){List<Role> list = new List<Role>();var count = 1000;for (int i = 0; i < count; i++){var entity = new Role(){RoleName = "普通员工" + i};context.Roles.Add(entity);context.SaveChanges();}}}/// <summary>/// 初看,觉得,这样做( context.SaveChanges()方在for循环外面)挺好的,/// 实际跟踪slq发现,还是执行了1000的插入操作,只不过没有在for循环里面;/// 而是在我们的for循环外;总结:不可取;/// </summary>static void CreateBluckInsertData1(){using (var context = new SiteDbContext()){List<Role> list = new List<Role>();var count = 1000;for (int i = 0; i < count; i++){var entity = new Role(){RoleName = "普通员工" + i};context.Roles.Add(entity);}context.SaveChanges();//会增加与数据库的交互次数//EF的一个上下文在提交时会打开一个数据连接,然后把转换成的SQL语句一条一条的发到数据库端,然后去提交
            }}/// <summary>/// 拼接字符串;组装后一次性操作;确定,传递的字符数量就会很多;网络压力增加;但不管怎样都比上面两张好;/// </summary>static void CreateBluckInsertData2(){Stopwatch watch = Stopwatch.StartNew();var count = 92000;using (var context = new SiteDbContext()){var bluckString = new StringBuilder();for (int i = 0; i < count; i++){bluckString.Append("INSERT INTO ROLES(RoleName) VALUES('");bluckString.Append("WORKER");bluckString.Append(i);bluckString.Append("');");}var result = bluckString.ToString();Console.WriteLine(string.Format("拼接字符串花费的时间:{0} milliseconds.",watch.ElapsedMilliseconds));//然后这里再来一次性批量的进行插入操作;
                watch.Restart();context.Database.ExecuteSqlCommand(result);//这样做的好处就是,可以一次性,全部插入,缺点就是;发送大量的insert 文本信息;//1000 customers are created, cost 1777 milliseconds.//5000 customers are created, cost 1906 milliseconds.//9000 customers are created, cost 2354 milliseconds.//9000 customers are created, cost 2023 milliseconds.//这样的计算比较草率;
            }watch.Stop();Console.WriteLine(string.Format("{0} customers are created, cost {1} milliseconds.", count.ToString(), watch.ElapsedMilliseconds));//结果:拼接字符串花费的时间:97 milliseconds.//12000 customers are created, cost 2028 milliseconds.//拼接字符串花费的时间:99 milliseconds.//22000 customers are created, cost 2336 milliseconds.//拼接字符串花费的时间:118 milliseconds.//92000 customers are created, cost 6553 milliseconds.
        }/// <summary>/// 这里我们使用第三种方法;/// 网上提供的插件的方法;/// 你以为,插件的方法,就是单纯的封装上面的操作?太年轻了,俺都没监测到一条insert 语句;那么它是怎么做的呢?/// /// </summary>static void CreateBluckInsertData3(){Stopwatch watch = Stopwatch.StartNew();var count = 92000;using (var context = new SiteDbContext()){List<Role> list = new List<Role>();for (int i = 0; i < count; i++){var entity = new Role(){RoleName = "普通员工" + i};list.Add(entity);//context.Roles.Add(entity); //fuck stupid;
                }Console.WriteLine(string.Format("拼接对象花费的时间:{0} milliseconds.", watch.ElapsedMilliseconds));//然后这里再来一次性批量的进行插入操作;
                watch.Restart();context.BulkInsert(list);context.BulkSaveChanges();}watch.Stop();Console.WriteLine(string.Format("{0} customers are created, cost {1} milliseconds.", count.ToString(), watch.ElapsedMilliseconds));//1000 customers are created, cost 2865 milliseconds//5000 customers are created, cost 18207 milliseconds.//9000 customers are created, cost 51134 milliseconds. (发现是方法用错了,窝草).不要把 context.Roles.Add(entity); 添加在for循环中;//然后结果是这样的:9000 customers are created, cost 2320 milliseconds.//效率明显比上面的方法提高了很多;//由此可见,我们的批量,效果操作,并不由之前那种方法高呢;//拼接对象花费的时间:102 milliseconds.//12000 customers are created, cost 2238 milliseconds.//拼接对象花费的时间:101 milliseconds.    //22000 customers are created, cost 2258 milliseconds.///拼接对象花费的时间:123 milliseconds.// 92000 customers are created, cost 3054 milliseconds.//这种方式的优势就不断体现出来了;//总结,凭借,字段串额效果,要比拼接对象集合的效率要高一些;//然后,就是我们的
}//可能涉及到一些批量数据迁移的时候;///总结:public void Info(){//凭借字段串的效率比拼接对象List的效率要高一些;//方式2的缺点在于,要传送大量的sql语句到我们的db中去执行,//方式3的实现方式和方式一有着本质的区别;是通过;//是数据小于五万条的时候,方式2的效率高,随着数据量的增加;方式3的优势就体现出来了//如果实际的开发中遇到大数据的批量操作;建议还是是用插件方式,就是我们的的方式3;//ps 操作中犯了一个错,是list.add(entity) 而不是 context.Roles.Add(entity); //fuck stupid;
}static void Main(string[] args){HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();//CreateBluckInsertData1();//CreateDB();//CreateBluckInsertData3();// CreateBluckInsertData2();
Console.ReadLine();}

当然,这里还有我们的另外一种做法;

SqlBulkCopy 接口描述

Microsoft SQL Server 提供一个称为 bcp 的流行的命令提示符实用工具,用于将数据从一个表移动到另一个表(表既可以在同一个服务器上,也可以在不同服务器上)。 SqlBulkCopy 类允许编写提供类似功能的托管代码解决方案

似乎这种效率更高一些(不过,俺没有去测)

阅读资料后,发现,z的扩展插件使用的就是我们的sqlbulkcopy接口滴呀;

大致的流程如下:

  • 在SQL Server中创建一张临时表;
  • 使用.NET SqlBulkCopy将数据批量插入临时表;
  • 在临时表和目标表之间执行一条SQL语句;
  • 从SQL Server删除临时表。

参考文献:

http://www.cnblogs.com/gaochundong/p/entity_framework_bulk_insert_extension.html

这里有一偏使用心得:

https://www.cnblogs.com/mobydick/archive/2011/08/28/2155983.html

还有这个:

https://www.cnblogs.com/zfanlong1314/archive/2013/02/05/2892998.html

转载于:https://www.cnblogs.com/mc67/p/8011432.html

相关文章:

HDOJ 1157 HDU 1157 Who's in the Middle ACM 1157 IN HDU

MiYu原创, 转帖请注明 : 转载自 ______________白白の屋 题目地址:http://acm.hdu.edu.cn/showproblem.php?pid1157 题目描述:Whos in the MiddleTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2451 Accep…

Keras使用多个GPU并行

model Model(inputs[v_i, v_j], outputsoutput_list) model multi_gpu_model(model,4) model.compile(....) 主要就是第二句话中的 multi_gpu_model函数&#xff0c;会把数据和模型分到多个gpu上执行有个坑&#xff0c;就是整个程序导入keras时要么全部from keras import ...…

使用JackJSON 流式API 创建JSON串【学习记录】

教程网址&#xff1a;Jackson流式API 目标JSON串 原始JSON串 核心代码 思路&#xff1a;先将原始JSON串生成对应的对象&#xff0c;获取到其数据 package com.run.runlpwebdemo.utils;import java.io.IOException; import java.io.StringWriter; import java.util.List;impo…

Eclipse插件安装

clispe想必大家都很熟悉了&#xff0c;一般来说&#xff0c;eclipse 插件都是安装在plugins目录 下。不过这样一来&#xff0c;当安装了许多插件之后&#xff0c;eclipse变的很大&#xff0c;最主要的是不便 于更新和管理众多插件。用links 方式安装eclipse插件&#xff0c;可以…

linux 命令之文件读取,head, tail, tailf, sed

head 看文件的前100行head -100 filename tail/tailf查看文件的后100行tail -100 filename 或 tail -n 100 filename tailf filename tail -f filename sed sed -n 100,200p filename 这样你就可以只查看文件的第100行到第200行。 转载于:https://www.cnblogs.com/xiaoniu-…

软件使用[19]

1 -- 服务自动的原理2 -- 命令chkconfig使用方法chkconfig是Linux系统中基于命令行的服务管理工具&#xff0c;其用途是启用和禁用系统服务。 chkconfig --list [name] chkconfig --add name chkconfig --del name chkconfig [--level levels] name chkconfig [--level le…

ORA-01747: user.table.column, table.column 或列说明无效 异常解决方法总结

1.sql 拼接错误 比如多了个逗号&#xff0c;少了个引号什么的&#xff0c;大部分其实都是这个问题&#xff0c;还是多细心&#xff0c;复制粘贴的时候多看看。 2.sql语句中使用了 Oracle 声明的关键字 --查询数据库关键字select * from v$reserved_words;----查询表中是否有关键…

SpringBoot 获取 application.properties 文件中的内容方法 【学习记录】

1 . Value注解来获取配置的值 2. ConfigurationProperties注解

安装swoole

php需要安装swoole扩展 swoole4.3.2 cd /usr/local/src/wget https://pecl.php.net/get/swoole-4.3.2.tgztar -zxvf swoole-4.3.2.tgzmv swoole-4.3.2 swoolecd swoole/usr/local/php/bin/phpize# 增加php配置./configure --enable-openssl --enable-swoole --enable-http2 --e…

layUI 学习记录

1 点击导航栏跳转页面 <!DOCTYPE html> <html> <head><meta charset"utf-8"><meta name"viewport" content"widthdevice-width, initial-scale1, maximum-scale1"><title>layout 后台大布局 - Layui</ti…

分享个网盘,个人觉得很不错!

金山网盘&#xff1a;http://k.wps.cn 可以在电脑上虚拟一个盘&#xff0c;你要上传下载删除文件&#xff0c;可以直接在本地电脑上操作&#xff0c;就像用自己硬盘的一个分区或是U盘一样&#xff0c;操作方便&#xff0c;但速度肯定没硬盘U盘快了&#xff0c;真正速度取决于你…

JSP 学习笔记 3

八jsp 九个内置对象1.内置对象的描述这就个内置对象都是servlet API的类或者接口的实例。JSP把他们都初始化了。2.九个内置对象分别是l application: javax.servlet.ServletContext的实例&#xff0c;代表JSP所属WEB应用本身&#xff0c;用于JSP叶面之间&#xff0c;或…

空间新闻模块CSS

#mod_10024 { /* 国内新闻模块 */ } #mod_10024 .modtl { /* 题头左 */ } #mod_10024 .modtc { /* 题头中 */ } #mod_10024 .modtr { /* 题头右 */ } #mod_10024 .modtit { /* 模块标题 */ } #mod_10024 a.modact img { /* "编辑图标" */ } #mod_10024 a.modact,#mod…

Cordova入门系列(三)Cordova插件调用

上一章我们介绍了cordova android项目是如何运行的&#xff0c;这一章我们介绍cordova的核心内容&#xff0c;插件的调用。演示一个例子&#xff0c;通过cordova插件&#xff0c;去调用摄像头。 一、插件的安装以及基本信息&#xff1a; 我们先在项目中安装调用摄像头的插件cor…

LVS 介绍 原理

一、 LVS简介 LVS是Linux Virtual Server的简称&#xff0c;也就是Linux虚拟服务器, 是一个由章文嵩博士发起的自由软件项目&#xff0c;它的官方站点是www.linuxvirtualserver.org&#xff08;版本很久不更新了&#xff09;。 现在LVS已经是 Linux标准内核的一部分…

腾讯云 短信服务 【学习记录 】

github 链接 https://github.com/qcloudsms/qcloudsms_java/tree/master maven 要使用 qcloudsms_java 功能&#xff0c;需要在 pom.xml 中添加如下依赖&#xff0c; <dependency><groupId>com.github.qcloudsms</groupId><artifactId>qcloudsms<…

Coolite Toolkit学习笔记六:常用控件Accordion、ToolBar、ToolTip

一、Accordion控件 Accordion的功能非常适用&#xff0c;使用很简单&#xff0c;轻轻松松的就可以构建一个可折叠的界面展示应用效果。相信大多数做ASP.NET开发的朋友都使用过ASP.NET AJAX Control Toolkit&#xff0c;它里面也提供有Accordion控件&#xff0c;详细可以查…

与ObjectDataSource共舞

4&#xff0c;ORM组件XCode&#xff08;与ObjectDataSource共舞&#xff09; XCode为了能更方便的解决大部分问题&#xff0c;不得不“屈身”于ObjectDataSource。 先上一个经典例子&#xff08;ObjectDataSourceGridView&#xff09;&#xff08;ObjectDataSource&#xff09;…

2.4 Go语言基础之切片

本文主要介绍Go语言中切片&#xff08;slice&#xff09;及它的基本使用。 一、引子 因为数组的长度是固定的并且数组长度属于类型的一部分&#xff0c;所以数组有很多的局限性。 例如&#xff1a; func arraySum(x [3]int) int{sum : 0for _, v : range x{sum sum v}return …

java 文件下载 【学习记录】

工具类 public static Boolean downloadExcelFile(HttpServletResponse response, String fileName) {OutputStream output;File file new File(fileName);if (file.exists()) {try {FileInputStream fileInputStream new FileInputStream(file);BufferedInputStream buffe…

[UI自动化]:控制浏览器操作

控制浏览器窗口大小 . PC端执行自动化测试脚本大多的情况下是希望浏览器在全屏幕模式下执行&#xff0c;那么可以使用maximize_window()方法使打开的浏览器全屏显示 控制浏览器后退、前进 在使用浏览器浏览网页时&#xff0c;浏览器提供了后退和前进按钮&#xff0c;可以方便地…

在项目中使用Google Closure Compiler

现在的Web项目总是离不开大量JavaScript&#xff0c;而JS文件的体积也越来越大&#xff0c;也越来越影响页面的感知性能&#xff08;Perceived Performance&#xff09;。因此&#xff0c;我们会对JS文件进行压缩&#xff0c;一方面是使用Gzip&#xff0c;而另一方面则是去除JS…

文件服务器共享目录设置(二)

三、 设置磁盘配额及文件屏蔽 为了防止用户无限制的上传文件&#xff0c;或上传病毒木马等文件&#xff0c;还需要进一步加强安全设置。用磁盘配额来管理用户的文件夹空间&#xff0c;用文件屏蔽来阻止用户上传有风险的文件。 在win2003中&#xff0c;磁盘配额只能…

Codeforces 894.D Ralph And His Tour in Binary Country

D. Ralph And His Tour in Binary Countrytime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRalph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connect…

linux下获取系统时间 和 时间偏移

获取linux时间 并计算时间偏移 void getSystemTimer(void){#if 0 char *wdate[]{"Sun","Mon","Tue","Wed","Thu","Fri","Sat"} ; time_t timep; struct tm *p; time(&timep); pgmtime(&timep)…

使用git命令上传本地文件到GitHub上

1、官网下载git并且anz安装 2、在Github上申请账号 3、在本地使用git命令生成私钥和公钥 连续按三次 回车键 $ ssh-keygen -t rsa -C "账号"生成如图 将生成的公钥设置到github上 &#xff0c; 生成公钥的地址是 ./ssh &#xff08;C盘的用户目录&#xff09; 4…

POI解析Excel文件工具类

/*** 读取excel数据*/public static List<Map<String, Object>> exportListFromExcel(File file, int sheetNum) throws IOException { return exportListFromExcel(new FileInputStream(file), FilenameUtils.getExtension(file.getName()), sheetNum); } publ…

关于Bulk加载模式

Bulk加载模式是Informatica提供的一种高性能数据加载模式&#xff0c;它利用数据库底层机制&#xff0c;依靠调用数据库本身提供的Utility来进行数据的加载  该方式将绕过数据库的log记录&#xff0c;以此提高数据库加载性能&#xff0c;因此Bulk模式不能进行数据的Rollback操…

C#:CsvReader读取.CSV文件(转换成DataTable)

原文引用&#xff1a;https://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader using LumenWorks.Framework.IO.Csv;using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Text;using System.Threading.Tas…

Standup Timer的MVC模式及项目结构分析

前言 学习android一段时间了&#xff0c;为了进一步了解android的应用是如何设计开发的&#xff0c;决定详细研究几个开源的android应用。从一些开源应用中吸收点东西&#xff0c;一边进行量的积累&#xff0c;一边探索android的学习研究方向。这里我首先选择了jwood的Standup …