本系列原创博客代码已在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进阶(四)- 实现批量新增的更多相关文章

  1. MP实战系列(十九)之批量新增

    批量操作在实际开发中也应用非常多,例如批量下发优惠券.批量添加用户等. 以MyBatis为例,通常实现批量操作,有这么几种方式? 第一,单条插入sql语句,进行for循环遍历,基准条件是根据前端传过的 ...

  2. windows server 2019 域控批量新增不用,只看这一篇就够了,别的不用看

    windows server 2019 域控批量新增不用,只看这一篇就够了,别的不用看 1. 新建excel表格 A B C D E 姓 名 全名 登录名 密码 李 四 李四 李四 test123!@ ...

  3. mybatis,批量新增、修改,删除

    转载自:http://blog.csdn.net/sanyuesan0000/article/details/19998727 最近需要用到Mybatis批量新增oracle数据库,刚开始在网上找到的 ...

  4. JPA 批量新增

    1. 在实现类 增加 EntityManager 注入 private EntityManager em; @PersistenceContext(name = "EntityManager ...

  5. mybatis 学习笔记(4) —— 批量新增数据

    1.业务是从前台传入List<T> ,在controller层接受参数,并进行批量新增操作. 2.需要处理的细节 a) mybatis可以支持批量新增,注意数据表需要将主键设置成自增列. ...

  6. MyBatis批量新增和更新

    之前有开发任务一个接口里面有大量的数据新增和更新操作,导致十分缓慢.使用了批量操作之后速度有明显提升,几乎百倍千倍的速度提升. 博主之前统计过,通过普通接口一次数据库插入大概需要200ms,对于大量新 ...

  7. 网站开发进阶(四十四)input type="submit" 和"button"的区别

    网站开发进阶(四十四)input type="submit" 和"button"的区别   在一个页面上画一个按钮,有四种办法: 这就是一个按钮.如果你不写ja ...

  8. mxgraph进阶(四)mxGraph再启程

    mxgraph进阶(四)mxGraph再启程 前言   小论文Constructing User Interaction Behaviors Net from System Log. (AICE 20 ...

  9. Java进阶(四十七)Socket通信

    Java进阶(四十七)Socket通信   今天讲解一个 Hello Word 级别的 Java Socket 通信的例子.具体通讯过程如下: 先启动Server端,进入一个死循环以便一直监听某端口是 ...

随机推荐

  1. 代替ESXI的虚拟机解决方案proxmox

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/matengbing/article/de ...

  2. export,import ,export default

    a.js export var name="李四"; 或者: a.js var name1="李四"; var name2="张三"; ex ...

  3. Python3入门(十三)——常用内置模块之集合模块collections

    1.namedtuple 主要用来定义一种数据类型:它具有Tuple的不变性,而且又能通过属性来访问 例如定义坐标: from collections import namedtuple Point ...

  4. Linux记录-批量安装LNMP(转载)

    #!/bin/bash # Describe: This is a one - button installation service script # 提示:使用此脚本时,尽量先选择第一项配置Yum ...

  5. python中多层循环的一键退出

    在单层循环的退出中,使用break即能退出,那么多层循环呢?机智的人们使用flag标识符的方式,例如: a=['a',1,2,3,4] b=['b',1,2,3,4] c=['c',1,2,3,4] ...

  6. 增强篇4 CO01生产订单屏幕增强

    Step1. 结构 CO_AUFK 里增加自定义字段:ZZZ_TRIAL 然后激活结构 查看AUFK是激活状态, 字段增强完成: Step2. CMOD  使用客户增强:PPCO0012    生产订 ...

  7. MongoDB学习笔记一:MongoDB基础

    目录 MongoDB是什么? 学了有什么用? MongoDB入门 安装 修改数据库位置 MongoDB的启动方式 MongoDB的图形化工具 MongoDB基本命令 增 查询 更新 删除 排序 投影 ...

  8. FormsAuthentication使用指南

    配置安全鉴别 鉴别是指鉴定来访用户是否合法的过程.ASP.NET Framework支持三种鉴别类型: Windows鉴别: NET Passport鉴别: Forms鉴别. 对于某一特定的应用程序, ...

  9. 高级UI-沉浸式设计

    关于沉浸式设计,在国内指的是Toolbar和系统状态栏相统一,而谷歌官方给出的沉浸式则是指整个界面为UI所用,而这里所说的沉浸式则是指的前者,涉及4.4和5.0及以上,4.4以下的Android做不出 ...

  10. Jira 自定义工作流并设置触发器

    一.添加修改工作流 打开 设置--问题--工作流 复制一个工作流,然后进去编辑页面 添加状态 增加转换动作 切换到文本,设置跳转过程中的事件 针对Stop Progress事件,修改跳转界面(界面需先 ...