本系列原创博客代码已在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. python中修改列表元素的方法

    一.在for循环中直接更改列表中元素的值不会起作用: 如: l = list(range(10)[::2]) print (l) for n in l: n = 0 print (l) 运行结果: [ ...

  2. Android平台云端打包证书使用说明

    原贴:https://ask.dcloud.net.cn/article/35985 Android平台云端打包证书使用说明 分类:HBuilderX 证书 Android 签名证书是一个应用的所有者 ...

  3. Flutter利用GridView实现网格的商品布局

    GridView.count 生成的是静态网格 效果: 代码: import 'package:flutter/material.dart'; void main() { runApp(MyApp() ...

  4. 泡泡一分钟:Visual Odometry Using a Homography Formulation with Decoupled Rotation and Translation Estimation Using Minimal Solutions

    张宁 Visual Odometry Using a Homography Formulation with Decoupled Rotation and Translation Estimation ...

  5. Docker容器(二)——镜像制作

    制作Docker镜像有两种方式:第一种.docker commit,保存容器(Container)的当前状态到镜像后,然后生成对应的image:第二种.docker build,使用Dockerfil ...

  6. Gson反序列json到实体类

    gson在基准测试过程中各项性能接近于Jackson(具体可以看Benchmark of Java JSON libraries)里面的测试, 本人亲测过,实测结果与他的数据一致,Jackson安全性 ...

  7. Form表单的传递与接收

    目录 表单的构建 后端接收 创建model 用Model接收表单的后端 表单的构建 我才知道这个东西,在开发中经常遇到表单的情况.一下子提交一串内容.表单元素 form,里面的内容必须有name字段. ...

  8. Swift4.0复习访问控制与作用域

    1.访问等级: open: 可以继承,可以重写. public: “public 访问等级能用于修饰所有文件作用域的函数.对象.协议.枚举.结构体.类以及各种类型中的属性与方法.用 public 所修 ...

  9. Docker 安装运行MySQL

    1.镜像主页 https://hub.docker.com/_/mysql 2.拉取5.7版本 docker pull mysql:5.7 3.或者拉取最新8.x版本 docker pull mysq ...

  10. 使用Maven为SpringBoot项目打包

    一.maven通过命令行打jar包 进入项目目录,执行如下命令: mvn -Dmaven.test.skip -U clean package 发现报如下错误: [ERROR] Failed to e ...