EntityFramework进阶(四)- 实现批量新增
本系列原创博客代码已在EntityFramework6.0.0测试通过,转载请标明出处
我们可以结合Ado.Net的SqlBulkCopy实现SqlServer数据库的批量新增,其他类型的数据库的批量操作请参考对应驱动提供的方法来自定义实现
public virtual void BulkInsert(TEntity[] entities,int? batchSize=,Action<object, SqlRowsCopiedEventArgs> copyProcess=null, string conn = null)
{
TDbContext _context = GetContext(conn);
var connection = (SqlConnection)_context.Database.Connection;
connection.Open();
Type type = typeof(TEntity); var objectContext = _context.GetObjectContext(); var workspace = objectContext.MetadataWorkspace; // var mappings = EntityMappingExtensions.GetMappings(workspace, objectContext.DefaultContainerName, type.Name); var tableName = GetTableName<TEntity>(_context);
var bulkCopy = new SqlBulkCopy(connection) { DestinationTableName = tableName }; // Foreign key relations show up as virtual declared
// properties and we want to ignore these.
var properties = type.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
var table = new DataTable();
foreach (var property in properties)
{
Type propertyType = property.PropertyType; // Nullable properties need special treatment.
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
} // Since we cannot trust the CLR type properties to be in the same order as
// the table columns we use the SqlBulkCopy column mappings.
table.Columns.Add(new DataColumn(property.Name, propertyType));
var clrPropertyName = property.Name;
var tableColumnName = property.Name;
// var tableColumnName = mappings[property.Name];
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(clrPropertyName, tableColumnName));
} // Add all our entities to our data table
foreach (var entity in entities)
{
var e = entity;
table.Rows.Add(properties.Select(property =>
EntityMappingExtensions.GetPropertyValue(property.GetValue(e, null))).ToArray());
}
if (batchSize.HasValue)
{
bulkCopy.BatchSize = batchSize.Value;
}
if (copyProcess != null)
{
bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(copyProcess);
}
// send it to the server for bulk execution
bulkCopy.WriteToServer(table); connection.Close();
} private string GetTableName<T>(TDbContext context) where T : class
{
Type t = typeof(T);
var attributes=t.GetCustomAttributes(typeof(TableAttribute), true);
if (attributes.Length > )
{
return t.GetTypeInfo().GetCustomAttributes<TableAttribute>().FirstOrDefault().Name;
}
return t.Name;
//var dbSet = context.Set<T>();
//var sql = dbSet.ToString();
//var regex = new Regex(@"FROM (?.*) AS");
//var match = regex.Match(sql);
//return match.Groups["table"].Value;
}
后续会再补充批量更新,批量删除的方法,区别新增操作,更新和删除是通用于MySql,Oracle,SqlServer(暂时提供这三种数据库),会动态创建sql来实现,用户不必再手写sql或者依赖其他库了
EntityFramework进阶(四)- 实现批量新增的更多相关文章
- MP实战系列(十九)之批量新增
批量操作在实际开发中也应用非常多,例如批量下发优惠券.批量添加用户等. 以MyBatis为例,通常实现批量操作,有这么几种方式? 第一,单条插入sql语句,进行for循环遍历,基准条件是根据前端传过的 ...
- windows server 2019 域控批量新增不用,只看这一篇就够了,别的不用看
windows server 2019 域控批量新增不用,只看这一篇就够了,别的不用看 1. 新建excel表格 A B C D E 姓 名 全名 登录名 密码 李 四 李四 李四 test123!@ ...
- mybatis,批量新增、修改,删除
转载自:http://blog.csdn.net/sanyuesan0000/article/details/19998727 最近需要用到Mybatis批量新增oracle数据库,刚开始在网上找到的 ...
- JPA 批量新增
1. 在实现类 增加 EntityManager 注入 private EntityManager em; @PersistenceContext(name = "EntityManager ...
- mybatis 学习笔记(4) —— 批量新增数据
1.业务是从前台传入List<T> ,在controller层接受参数,并进行批量新增操作. 2.需要处理的细节 a) mybatis可以支持批量新增,注意数据表需要将主键设置成自增列. ...
- MyBatis批量新增和更新
之前有开发任务一个接口里面有大量的数据新增和更新操作,导致十分缓慢.使用了批量操作之后速度有明显提升,几乎百倍千倍的速度提升. 博主之前统计过,通过普通接口一次数据库插入大概需要200ms,对于大量新 ...
- 网站开发进阶(四十四)input type="submit" 和"button"的区别
网站开发进阶(四十四)input type="submit" 和"button"的区别 在一个页面上画一个按钮,有四种办法: 这就是一个按钮.如果你不写ja ...
- mxgraph进阶(四)mxGraph再启程
mxgraph进阶(四)mxGraph再启程 前言 小论文Constructing User Interaction Behaviors Net from System Log. (AICE 20 ...
- Java进阶(四十七)Socket通信
Java进阶(四十七)Socket通信 今天讲解一个 Hello Word 级别的 Java Socket 通信的例子.具体通讯过程如下: 先启动Server端,进入一个死循环以便一直监听某端口是 ...
随机推荐
- Python3基础 函数 多值参数 元组与字典形式(键值对分别指出)
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- C++ STL中常见容器的时间复杂度和比较和分析
C++ STL中常见容器的时间复杂度 map, set, multimap, and multiset 上述四种容器采用红黑树实现,红黑树是平衡二叉树的一种.不同操作的时间复杂度近似为: 插入: O( ...
- java-mybaits-014-数据库缓存设计【querycache、mybatis一级缓存、二级缓存】
一.概述 一般来说,可以在5个方面进行缓存的设计: 1.最底层可以配置的是数据库自带的query cache, 2.mybatis的一级缓存,默认情况下都处于开启状态,只能使用自带的Perpetual ...
- Source Insight 4.0配置格式化工具AStyle.exe
Source Insight 4.0配置格式化工具AStyle.exe 摘自:https://blog.csdn.net/u012156133/article/details/81566871 1. ...
- lombok 插件安装使用
Lombok是一个Java库,它自动插入编辑器并构建工具,为Java添加香料.永远不要再编写另一个getter或Eques方法,您的类有一个功能齐全的构建器,可以自动化您的日志变量以及更多的注释. 官 ...
- F5 BIG-IP – Useful SNMP oids to monitor
I have collected some of the most interesting OIDs (in my scenario im using LTM and APM modules) fro ...
- Python - Django - ORM 聚合查询和分组查询
models.py: from django.db import models # 出版社 class Publisher(models.Model): id = models.AutoField(p ...
- (二十三)IDEA 构建一个springboot工程,以及可能遇到的问题
一.下载安装intellij IEDA 需要破解 二.创建springboot工程 其他步骤省略,创建好的工程结构如下图: 三.配置springoboot工程 3.1 如上图src/main目录下只有 ...
- 【 Linux 】Systemd 配置文件说明及编写(2)
1. 开机启动 对于支持 systemd 的软件,如果想要设置开机启动,就执行如下命令(以 http 为例): systemctl enable httpd 上面的命令相当于在 /etc/system ...
- Ubuntu开发环境配置
主要是: 源的更新 安装vim编辑器 远程登录xrdp相关配置 synergy symless键鼠共享配置 对新买的硬盘进行格式化和分区 vsftp环境搭建 gcc开发环境配置 qt5开发环境配置 m ...