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端,进入一个死循环以便一直监听某端口是 ...
随机推荐
- python制作简单excel统计报表1之with的简单用法
# coding=utf-8 def open_file(): """使用with打开一个文件""" # 普通操作文件方法 # f = op ...
- Python3基础 bool True为1 False为0
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- Qt编写气体安全管理系统21-探测器管理
一.前言 探测器在整个系统中是最核心的关键的硬件,终端节点硬件,安装有探测芯片装置,负责探测前端对应气体浓度,并记录值,等待控制器轮训数据回复,控制器信息表也是字段最多的,要存储位号.控制器名称.探测 ...
- Qt编写气体安全管理系统6-地图监控
一.前言 地图监控主要是提供一个地图(可以是平面的也可以是立体彩色的,一般建议鸟瞰图,有3D感),然后设备在对应的地图上,可以切换地图来查看对应区域的设备,一般来说一个区域会有一个地图文件,设备在地图 ...
- 【WebView】Android WebView中的Cookie操作
Hybrid App(混合式应用)的开发过程中少不了与WebView的交互,在涉及到账户体系的产品中,包含了一种登录状态的传递.比如,在Native(原生)界面的登录操作,进入到Web界面时,涉及到账 ...
- PAT 甲级 1065 A+B and C (64bit) (20 分)(溢出判断)*
1065 A+B and C (64bit) (20 分) Given three integers A, B and C in [−], you are supposed to tell whe ...
- axios发了两次请求
一.问题描述 用axios发post请求,却出现了options请求和post请求,options请求哪里来的? 二.问题分析 1.先温习一下跨域的知识 2.axios默认类型是Content-Typ ...
- No section matches selector - no section to be FIRST/LAST
1. 使用KEIL MDK ,STM32F405RG,编译的时候报错 .\Objects\ks3620_stm32f405_proj.sct(): error: L6236E: No section ...
- python 调 java(胶水就是胶水)
java门外汉用python调java, 一.安装java环境(linux) 1.首先要去下载好JDK,Java SE 8的官方网址是http://www.oracle.com/technetwork ...
- 在ensp上配置通过Stelnet登录系统
我们为什么我们要采用Stelent登录? 因为不安全,我们要采用更加安全的方式,双向加密,通过ssh网络安全协议 下面我们开始实验:使用路由器R1模拟PC,作为SSH的客户端:路由器R2作为SSH的服 ...