EFcore 使用 EFCore.BulkExtensions(不支持mysql)或 EntityFramework-Plus 批量增加、删除、修改
EFCore.BulkExtensions,EntityFramework-Plus 都是Microsoft推荐的EFcore扩展 。
可以通过nuget安装
一、EFCore.BulkExtensions
使用方法如下:
实体批量操作:
context.BulkInsert(entitiesList); context.BulkInsertAsync(entitiesList); context.BulkUpdate(entitiesList); context.BulkUpdateAsync(entitiesList); context.BulkDelete(entitiesList); context.BulkDeleteAsync(entitiesList); context.BulkInsertOrUpdate(entitiesList); context.BulkInsertOrUpdateAsync(entitiesList); //Upsert context.BulkInsertOrUpdateOrDelete(entitiesList); context.BulkInsertOrUpdateOrDeleteAsync(entitiesList); //Sync context.BulkRead(entitiesList); context.BulkReadAsync(entitiesList); context.Truncate<Entity>(); context.TruncateAsync<Entity>();
按条件批量操作
// Delete context.Items.Where(a => a.ItemId > 500).BatchDelete(); context.Items.Where(a => a.ItemId > 500).BatchDeleteAsync(); // Update (using Expression arg.) supports Increment/Decrement context.Items.Where(a => a.ItemId <= 500).BatchUpdate(a => new Item { Quantity = a.Quantity + 100 }); // can be as value '+100' or as variable '+incrementStep' (int incrementStep = 100;) // Update (via simple object) context.Items.Where(a => a.ItemId <= 500).BatchUpdate(new Item { Description = "Updated" }); context.Items.Where(a => a.ItemId <= 500).BatchUpdateAsync(new Item { Description = "Updated" }); // Update (via simple object) - requires additional Argument for setting to Property default value var updateColumns = new List<string> { nameof(Item.Quantity) }; // Update 'Quantity' to default value('0'-zero) var q = context.Items.Where(a => a.ItemId <= 500); int affected = q.BatchUpdate(new Item { Description = "Updated" }, updateColumns);//result assigned to variable
当直接使用这些操作是独立的事务和自动提交。不需要手动savechange
然后如果我们需要多个操作单一过程应该使用显式事务。如下
using (var connection = (SqliteConnection)context.Database.GetDbConnection()) { connection.Open(); using (var transaction = connection.BeginTransaction()) { var bulkConfig = new BulkConfig() { SqliteConnection = connection, SqliteTransaction = transaction }; context.BulkInsert(entities, bulkConfig); context.BulkInsert(subEntities, bulkConfig); transaction.Commit(); } }
插件源码在 github
二、EntityFramework-Plus
主要是mssql和mysql都支持
// using Z.EntityFramework.Plus; // Don't forget to include this. // DELETE all users which has been inactive for 2 years ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2)) .Delete(); // DELETE using a BatchSize ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2)) .Delete(x => x.BatchSize = 1000); // using Z.EntityFramework.Plus; // Don't forget to include this. // UPDATE all users which has been inactive for 2 years ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2)) .Update(x => new User() { IsSoftDeleted = 1 });