|
| 1 | +# Bulk Operations |
| 2 | + |
| 3 | +EfCoreKit provides high-performance batch operations that execute in a single database round trip instead of one command per row. |
| 4 | + |
| 5 | +## Supported Operations |
| 6 | + |
| 7 | +| Method | Description | |
| 8 | +|--------|-------------| |
| 9 | +| `BulkInsertAsync<T>` | Insert thousands of rows in one call | |
| 10 | +| `BulkUpdateAsync<T>` | Update many rows by primary key | |
| 11 | +| `BulkDeleteAsync<T>` | Delete many rows by primary key | |
| 12 | +| `BulkUpsertAsync<T>` | Insert or update (merge) based on key match | |
| 13 | + |
| 14 | +## Supported Databases |
| 15 | + |
| 16 | +Each database has its own provider package with an optimized implementation: |
| 17 | + |
| 18 | +| Package | Database | Registration | |
| 19 | +|---------|----------|-------------| |
| 20 | +| `EfCoreKit.SqlServer` | SQL Server 2016+ | `services.AddEfCoreKitSqlServer()` | |
| 21 | +| `EfCoreKit.PostgreSql` | PostgreSQL 12+ | `services.AddEfCoreKitPostgreSql()` | |
| 22 | +| `EfCoreKit.MySql` | MySQL 8.0+ | `services.AddEfCoreKitMySql()` | |
| 23 | +| `EfCoreKit.Sqlite` | SQLite 3.x | `services.AddEfCoreKitSqlite()` | |
| 24 | + |
| 25 | +Or install `EfCoreKit` (umbrella package) to get all providers at once. |
| 26 | + |
| 27 | +## Setup |
| 28 | + |
| 29 | +```csharp |
| 30 | +builder.Services.AddEfCoreKit<AppDbContext>( |
| 31 | + options => options.UseSqlServer(connectionString)); |
| 32 | + |
| 33 | +// Register the bulk operations provider |
| 34 | +builder.Services.AddEfCoreKitSqlServer(); |
| 35 | +``` |
| 36 | + |
| 37 | +## Usage |
| 38 | + |
| 39 | +Inject `IBulkExecutor` and use it with your `DbContext`: |
| 40 | + |
| 41 | +```csharp |
| 42 | +public class OrderService |
| 43 | +{ |
| 44 | + private readonly AppDbContext _context; |
| 45 | + private readonly IBulkExecutor _bulk; |
| 46 | + |
| 47 | + public OrderService(AppDbContext context, IBulkExecutor bulk) |
| 48 | + { |
| 49 | + _context = context; |
| 50 | + _bulk = bulk; |
| 51 | + } |
| 52 | + |
| 53 | + public async Task ImportOrders(List<Order> orders) |
| 54 | + { |
| 55 | + await _bulk.BulkInsertAsync(_context, orders); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +### Insert |
| 61 | + |
| 62 | +```csharp |
| 63 | +var customers = Enumerable.Range(1, 10_000) |
| 64 | + .Select(i => new Customer { Name = $"Customer {i}" }) |
| 65 | + .ToList(); |
| 66 | + |
| 67 | +await bulk.BulkInsertAsync(context, customers); |
| 68 | +``` |
| 69 | + |
| 70 | +### Update |
| 71 | + |
| 72 | +```csharp |
| 73 | +// Load entities, modify them, then bulk update |
| 74 | +var products = await context.Products.Where(p => p.Category == "Sale").ToListAsync(); |
| 75 | +foreach (var p in products) p.Price *= 0.9m; // 10% off |
| 76 | +
|
| 77 | +await bulk.BulkUpdateAsync(context, products); |
| 78 | +``` |
| 79 | + |
| 80 | +### Delete |
| 81 | + |
| 82 | +```csharp |
| 83 | +var expired = await context.Orders.Where(o => o.ExpiresAt < DateTime.UtcNow).ToListAsync(); |
| 84 | +await bulk.BulkDeleteAsync(context, expired); |
| 85 | +``` |
| 86 | + |
| 87 | +### Upsert (Insert or Update) |
| 88 | + |
| 89 | +```csharp |
| 90 | +// Inserts new rows, updates existing ones (matched by primary key) |
| 91 | +await bulk.BulkUpsertAsync(context, incomingProducts); |
| 92 | +``` |
| 93 | + |
| 94 | +## BulkConfig Options |
| 95 | + |
| 96 | +All operations accept an optional `BulkConfig` for fine-tuning: |
| 97 | + |
| 98 | +```csharp |
| 99 | +await bulk.BulkInsertAsync(context, customers, new BulkConfig |
| 100 | +{ |
| 101 | + BatchSize = 5000, // Rows per batch (default: 1000) |
| 102 | + Timeout = 60, // Seconds (default: 30) |
| 103 | + PreserveInsertOrder = true, // Maintain list order (default: true) |
| 104 | + SetOutputIdentity = true, // Populate generated IDs after insert |
| 105 | + UseTransaction = true, // Wrap in transaction (default: true) |
| 106 | + TrackEntities = false, // Add to EF change tracker after operation |
| 107 | +
|
| 108 | + // Column control |
| 109 | + PropertiesToInclude = ["Name", "Email"], // Only update these columns |
| 110 | + PropertiesToExclude = ["CreatedAt"], // Skip these columns |
| 111 | +
|
| 112 | + // Upsert key |
| 113 | + UpdateByProperties = ["ExternalId"], // Match on this instead of PK |
| 114 | +
|
| 115 | + // Progress reporting |
| 116 | + OnProgress = (processed, total) => |
| 117 | + Console.WriteLine($"{processed}/{total}") |
| 118 | +}); |
| 119 | +``` |
| 120 | + |
| 121 | +### BulkConfig Properties |
| 122 | + |
| 123 | +| Property | Default | Description | |
| 124 | +|----------|---------|-------------| |
| 125 | +| `BatchSize` | 1000 | Number of rows per batch | |
| 126 | +| `Timeout` | 30 | Command timeout in seconds | |
| 127 | +| `PreserveInsertOrder` | `true` | Maintain the order of the input list | |
| 128 | +| `SetOutputIdentity` | `false` | Populate auto-generated keys after insert | |
| 129 | +| `UpdateByProperties` | `null` | Columns to match on for upsert (defaults to PK) | |
| 130 | +| `PropertiesToInclude` | `null` | Only include these columns | |
| 131 | +| `PropertiesToExclude` | `null` | Exclude these columns | |
| 132 | +| `UseTransaction` | `true` | Wrap operation in a transaction | |
| 133 | +| `TrackEntities` | `false` | Add entities to the change tracker after the operation | |
| 134 | +| `OnProgress` | `null` | Callback for progress reporting `(processed, total)` | |
| 135 | + |
| 136 | +## Performance Notes |
| 137 | + |
| 138 | +- Bulk operations bypass the EF Core change tracker — they go directly to the database |
| 139 | +- `BulkInsertAsync` with 10,000 rows is typically **10-50x faster** than `AddRange` + `SaveChanges` |
| 140 | +- Set `BatchSize` based on your row size — larger rows benefit from smaller batches |
| 141 | +- `SetOutputIdentity = true` adds overhead (an extra round trip) but populates generated keys |
| 142 | +- Interceptors (audit, soft delete) do **not** apply to bulk operations since they bypass `SaveChanges` |
1 | 143 |
|
0 commit comments