本系列原创博客代码已在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. Ionic4.x ion-infinite-scroll 上拉分页加载更多

    <ion-header> <ion-toolbar> <ion-title> Tab One </ion-title> </ion-toolbar ...

  2. CDH 部署 Hadoop:5.开始安装

    Cloudera Enterprise 6.2.x   或者参考https://blog.csdn.net/shawnhu007/article/details/52579204 第零步:优化相关 e ...

  3. 在gitlab新建分支,IDEA切换时找不到的解决办法

    VCS——>Git——>Fetch

  4. iOS 给view,button,text filed,label等添加边框和颜色

    self.tfaaa.layer.borderWidth = 2; self.tfaaa.layer.borderColor = [UIColor blueColor].CGColor;

  5. Flutter Bloc状态管理 简单上手

    我们都知道,Flutter中Widget的状态控制了UI的更新,比如最常见的StatefulWidget,通过调用setState({})方法来刷新控件.那么其他类型的控件,比如StatelessWi ...

  6. Swoole练习 Web

    WEB 服务端代码 $http = new swoole_http_server("0.0.0.0", 9501); $http->on('request', functio ...

  7. pycharm 提示:this license **** has been cancelled(2)

    pycharm安装激活过程中,提示 this license **** has been cancelled .这个问题并不是你的激活码不对,而是需要修改系统的hosts文件,下面详细讲解下如何修改h ...

  8. nvidia jetson tx2 刷机遇到的问题解决

    一.主要信息 使用的开发板:nvidia jetson tx2(内存8g有wifi的版本) 使用的JetPack版本: 4.2.2 二.遇到的问题及解决 1. 刷好jetson os 后,开发板一直在 ...

  9. Django源码分析之启动wsgi发生的事

    前言 ​ 好多人对技术的理解都停留在懂得使用即可,因而只会用而不会灵活用,俗话说好奇害死猫,不然我也不会在凌晨1.48的时候决定写这篇博客,好吧不啰嗦了 ​ 继续上一篇文章,后我有个问题(上文:&qu ...

  10. 020 Android 常用颜色对应表

    1.Android colors.xml常用颜色汇总 <?xml version="1.0" encoding="utf-8"?> <reso ...