EFCore.BulkExtensions.MIT.SqlServer 8.17.0

dotnet add package EFCore.BulkExtensions.MIT.SqlServer --version 8.17.0                
NuGet\Install-Package EFCore.BulkExtensions.MIT.SqlServer -Version 8.17.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="EFCore.BulkExtensions.MIT.SqlServer" Version="8.17.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add EFCore.BulkExtensions.MIT.SqlServer --version 8.17.0                
#r "nuget: EFCore.BulkExtensions.MIT.SqlServer, 8.17.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install EFCore.BulkExtensions.MIT.SqlServer as a Cake Addin
#addin nuget:?package=EFCore.BulkExtensions.MIT.SqlServer&version=8.17.0

// Install EFCore.BulkExtensions.MIT.SqlServer as a Cake Tool
#tool nuget:?package=EFCore.BulkExtensions.MIT.SqlServer&version=8.17.0                

EFCore.BulkExtensions.MIT

This is MIT fork of EFCore.BulkExtensions.

Why?

Original project changed it's license to dual license (commercial and free only under certain conditions). This fork is distributed under MIT license.

When?

I forked the project at commit 5bf938a422 from 18.01.2023. This is the last version with the MIT license.

Why choose this fork instead of original version?

Why choose original version?

  • You need version below 6.x. My fork supports only EFCore 6+.
  • There might be some new features, missing here. But feel free to create feature request (or even better create PR yourself).

What's changed?

  • Test are now run using TestContainers, hassle free setup (only Docker needed). So any contribution should be very easy.
  • Tests are now run as part of release process (see GitHub Actions for yourself).
  • Tests are run against all versions, so no regressions should happen.

EFCore.BulkExtensions.MIT

EntityFrameworkCore extensions: <br> -Bulk operations (Insert, Update, Delete, Read, Upsert, Sync, SaveChanges)<br> -Batch ops (Delete, Update) and Truncate.<br> Library is Lightweight and very Efficient, having all mostly used CRUD operation.<br>

Latest version is using EF Core 8 and targeting .Net 8.<br> Supports all 4 major databases:<br> -SQLServer (or SqlAzure) under the hood uses SqlBulkCopy for Insert, Update/Delete = BulkInsert + raw Sql MERGE.<br> -PostgreSQL (9.5+) is using COPY BINARY combined with ON CONFLICT for Update (supported from v6+).<br> -MySQL (8+) is using MySqlBulkCopy combined with ON DUPLICATE for Update (Only Bulk ops supported from v6+).<br> -SQLite has no Copy tool, instead library uses plain SQL combined with UPSERT.<br> Bulk Tests can not have UseInMemoryDb because InMemoryProvider does not support Relational-specific methods.<br> Instead Test options are SqlServer(Developer or Express), LocalDb(if alongside Developer v.), or for other adapters PostgreSQL/MySQL/SQLite.

Available on <a href="https://www.nuget.org/packages/EFCore.BulkExtensions.MIT/"><img src="https://buildstats.info/nuget/EFCore.BulkExtensions.MIT" /></a><br> That is main nuget for all Databases, there are also specific ones with single provider for those who need small packages.<br> Package manager console command for installation: Install-Package EFCore.BulkExtensions<br> Its assembly is Strong-Named and Signed with a key. | Nuget | Target | Used EF v. | For projects targeting | | ----- | --------------- | ----------- | ------------------------------- | | 8.x | Net 8.0 | EF Core 8.0 | Net 8.0+ | | 7.x | Net 6.0 | EF Core 7.0 | Net 7.0+ | | 6.x | Net 6.0 | EF Core 6.0 | Net 6.0+ | | 5.x | N/A | N/A | N/A | | 3.x | N/A | N/A | N/A |

Prior versions (5 and lower) are no longer actively maintained.

Contributing

If you find this project useful you can mark it by leaving a Github Star ⭐.</br>

Please read CONTRIBUTING for details on code of conduct, and the process for submitting pull requests.<br> Button<br>

Usage

It's pretty simple and straightforward.<br> Bulk Extensions are made on DbContext and are used with entities List (supported both regular and Async methods):

context.BulkInsert(entities);                 context.BulkInsertAsync(entities);
context.BulkInsertOrUpdate(entities);         context.BulkInsertOrUpdateAsync(entities);         // Upsert
context.BulkInsertOrUpdateOrDelete(entities); context.BulkInsertOrUpdateOrDeleteAsync(entities); // Sync
context.BulkUpdate(entities);                 context.BulkUpdateAsync(entities);
context.BulkDelete(entities);                 context.BulkDeleteAsync(entities);
context.BulkRead(entities);                   context.BulkReadAsync(entities);
context.BulkSaveChanges();                    context.BulkSaveChangesAsync();                    // >= v6

-SQLite requires package: SQLitePCLRaw.bundle_e_sqlite3 with call to SQLitePCL.Batteries.Init()<br>

Batch Extensions are made on IQueryable DbSet and can be used as in the following code segment.<br> They are done as pure sql and no check is done whether some are prior loaded in memory and are being Tracked.<br> (updateColumns is optional param in which PropertyNames added explicitly when need update to it's default value)<br> Info about lock-escalation in SQL Server with Batch iteration example as a solution at the bottom of code segment.

// 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 });
context.Items.Where(a => a.ItemId <= 500).BatchUpdateAsync(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 updateCols = new List<string> { nameof(Item.Quantity) }; // Update 'Quantity' to default value ('0')
var q = context.Items.Where(a => a.ItemId <= 500);
int affected = q.BatchUpdate(new Item { Description="Updated" }, updateCols); // result assigned to aff.

// Batch iteration (useful in same cases to avoid lock escalation)
do {
    rowsAffected = query.Take(chunkSize).BatchDelete();
} while (rowsAffected >= chunkSize);

// Truncate
context.Truncate<Entity>();
context.TruncateAsync<Entity>();

Performances

Following are performances (in seconds)

  • For SQL Server (v. 2019):
Ops\Rows EF 100K Bulk 100K EF 1 MIL. Bulk 1 MIL.
Insert 11 s 3 s 60 s 15 s
Update 8 s 4 s 84 s 27 s
Delete 50 s 3 s 5340 s 15 s

TestTable has 6 columns (Guid, string x2, int, decimal?, DateTime), all inserted and 2 were updated.<br> Test done locally on configuration: INTEL i7-10510U CPU 2.30GHz, DDR3 16 GB, SSD SAMSUNG 512 GB.<br> For small data sets there is an overhead since most Bulk ops need to create Temp table and also Drop it after finish.<br> Probably good advice would be to use Bulk ops for sets greater than 1000.

Bulk info

If Windows Authentication is used then in ConnectionString there should be Trusted_Connection=True; because Sql credentials are required to stay in connection.<br>

When used directly each of these operations are separate transactions and are automatically committed.<br> And if we need multiple operations in single procedure then explicit transaction should be used, for example:<br>

using (var transaction = context.Database.BeginTransaction())
{
    context.BulkInsert(entities1List);
    context.BulkInsert(entities2List);
    transaction.Commit();
}

BulkInsertOrUpdate method can be used when there is need for both operations but in one connection to database.<br> It makes Update when PK(PrimaryKey) is matched, otherwise does Insert.<br>

BulkInsertOrUpdateOrDelete effectively synchronizes table rows with input data.<br> Those in Db that are not found in the list will be deleted.<br> Partial Sync can be done on table subset using expression set on config with method:<br> bulkConfig.SetSynchronizeFilter<Item>(a => a.Quantity > 0);<br> Not supported for SQLite(Lite has only UPSERT statement) nor currently for PostgreSQL. Way to achieve there sync functionality is to Select or BulkRead existing data from DB, split list into sublists and call separately Bulk methods for BulkInsertOrUpdate and Delete.

BulkRead (SELECT and JOIN done in Sql)<br> Useful when need to Select from big List based on Unique Prop./Columns specified in config UpdateByProperties<br>

// instead of WhereIN which will TimeOut for List with over around 40 K records
var entities = context.Items.Where(a => itemsNames.Contains(a.Name)).AsNoTracking().ToList(); // SQL IN
// or JOIN in Memory that loads entire table
var entities = context.Items.Join(itemsNames, a => a.Name, p => p, (a, p) => a).AsNoTracking().ToList();

// USE
var items = itemsNames.Select(a => new Item { Name = a }).ToList(); // Items list with only Name set
var bulkConfig = new BulkConfig { UpdateByProperties = new List<string> { nameof(Item.Name) } };
context.BulkRead(items, bulkConfig); // Items list will be loaded from Db with data(other properties)

Example of special use case when need to BulkRead child entities after BulkReading parent list.

SaveChanges uses Change Tracker to find all modified(CUD) entities and call proper BulkOperations for each table.<br> Because it needs tracking it is slower then pure BulkOps but still much faster then regular SaveChanges.<br> With config OnSaveChangesSetFK setting FKs can be controlled depending on whether PKs are generated in Db or in memory.<br> Support for this method was added in version 6 of the library.<br> Before calling this method newly created should be added into Range:

context.Items.AddRange(newEntities); // if newEntities is parent list it can have child sublists
context.BulkSaveChanges();

Practical general usage could be made in a way to override regular SaveChanges and if any list of Modified entities entries is greater then say 1000 to redirect to Bulk version.

Note: Bulk ops have optional argument Type type that can be set to type of Entity if list has dynamic runtime objects or is inherited from Entity class.

BulkConfig arguments

Bulk methods can have optional argument BulkConfig with properties (bool, int, object, List<string>):<br>

PROPERTY : DEFAULTvalue
----------------------------------------------------------------------------------------------
PreserveInsertOrder: true,                    PropertiesToInclude: null,
SetOutputIdentity: false,                     PropertiesToIncludeOnCompare: null,
BatchSize: 2000,                              PropertiesToIncludeOnUpdate: null,
NotifyAfter: null,                            PropertiesToExclude: null,
BulkCopyTimeout: null,                        PropertiesToExcludeOnCompare: null,
EnableStreaming: false,                       PropertiesToExcludeOnUpdate: null,
UseTempDB: false,                             UpdateByProperties: null,
UniqueTableNameTempDb: true,                  EnableShadowProperties: false,
CustomDestinationTableName: null,             IncludeGraph: false,
CustomSourceTableName: null,                  OmitClauseExistsExcept: false,
CustomSourceDestinationMappingColumns: null,  DoNotUpdateIfTimeStampChanged: false,
TrackingEntities: false,                      SRID: 4326,
WithHoldlock: true,                           DateTime2PrecisionForceRound: false,
CalculateStats: false,                        TemporalColumns: { "PeriodStart", "PeriodEnd" },
SqlBulkCopyOptions: Default,                  OnSaveChangesSetFK: true, // Not supported on MySQL
SqlBulkCopyColumnOrderHints: null,            IgnoreGlobalQueryFilters: false,
OnConflictUpdateWhereSql: null,               ReplaceReadEntities: false,
----------------------------------------------------------------------------------------------
METHOD: SetSynchronizeFilter<T>

If we want to change defaults, BulkConfig should be added explicitly with one or more bool properties set to true, and/or int props like BatchSize to different number.<br> Config also has DelegateFunc for setting Underlying-Connection/Transaction, e.g. in UnderlyingTest.<br> When doing update we can chose to exclude one or more properties by adding their names into PropertiesToExclude, or if we need to update less then half column then PropertiesToInclude can be used. Setting both Lists are not allowed.

When using the BulkInsert_/OrUpdate methods, you may also specify the PropertiesToIncludeOnCompare and PropertiesToExcludeOnCompare properties. By adding a column name to the PropertiesToExcludeOnCompare, will allow it to be inserted and updated but will not update the row if any of the other columns in that row did not change. For example, if you are importing bulk data and want to keep an internal CreateDate or UpdateDate, you add those columns to the PropertiesToExcludeOnCompare.<br> Another option that may be used in the same scenario are the PropertiesToIncludeOnUpdate and PropertiesToExcludeOnUpdate properties. These properties will allow you to specify insert-only columns such as CreateDate and CreatedBy.

If we want Insert only new and skip existing ones in Db (Insert_if_not_Exist) then use BulkInsertOrUpdate with config PropertiesToIncludeOnUpdate = new List<string> { "" }

Additionally there is UpdateByProperties for specifying custom properties, by which we want update to be done.<br> When setting multiple props in UpdateByProps then match done by columns combined, like unique constrain based on those cols.<br> Using UpdateByProperties while also having Identity column requires that Id property be Excluded.<br> Also with PostgreSQL when matching is done it requires UniqueIndex so for custom UpdateByProperties that do not have Un.Ind., it is temporarily created in which case method can not be in transaction (throws: current transaction is aborted; CREATE INDEX CONCURRENTLY cannot run inside a transaction block).<br> Similar is done with MySQL by temporarily adding UNIQUE CONSTRAINT.<br>

If NotifyAfter is not set it will have same value as BatchSize while BulkCopyTimeout when not set has SqlBulkCopy default which is 30 seconds and if set to 0 it indicates no limit.<br><br> SetOutputIdentity have purpose only when PK has Identity (usually int type with AutoIncrement), while if PK is Guid(sequential) created in Application there is no need for them.<br> Also Tables with Composite Keys have no Identity column so no functionality for them in that case either.

var bulkConfig = new BulkConfig { SetOutputIdentity = true, BatchSize = 4000 };
context.BulkInsert(entities, bulkConfig);
context.BulkInsertOrUpdate(entities, new BulkConfig { SetOutputIdentity = true });
context.BulkInsertOrUpdate(entities, b => b.SetOutputIdentity = true); // e.g. BulkConfig with Action arg.

PreserveInsertOrder is true by default and makes sure that entities are inserted to Db as ordered in entitiesList.<br> When table has Identity column (int autoincrement) with 0 values in list they will temporary be automatically changed from 0s into range -N:-1.<br> Or it can be manually set with proper values for order (Negative values used to skip conflict with existing ones in Db).<br> Here single Id value itself doesn't matter, db will change it to next in sequence, what matters is their mutual relationship for sorting.<br> Insertion order is implemented with TOP in conjunction with ORDER BY. stackoverflow:merge-into-insertion-order.<br> This config should remain true when SetOutputIdentity is set to true on Entity containing NotMapped Property. issues/76<br> When using SetOutputIdentity Id values will be updated to new ones from database.<br> With BulkInsertOrUpdate for those that will be updated it has to match with Id column, or other unique column(s) if using UpdateByProperties in which case orderBy is done with those props instead of ID.<br> For Sqlite combination of BulkInsertOrUpdate and IdentityId automatic set will not work properly since it does not have full MERGE capabilities like SqlServer. Instead list can be split into 2 lists, and call separately BulkInsert and BulkUpdate.<br>

SetOutputIdentity (not supported for MySQL) is useful when BulkInsert is done to multiple related tables, that have Identity column.<br> After Insert is done to first table, we need Id-s (if using Option 1) that were generated in Db because they are FK(ForeignKey) in second table.<br> It is implemented with OUTPUT as part of MERGE Query, so in this case even the Insert is not done directly to TargetTable but to TempTable and then Merged with TargetTable.<br> When used Id-s will be updated in entitiesList, and if PreserveInsertOrder is set to false then entitiesList will be cleared and reloaded.<br> Example of SetOutputIdentity with parent-child FK related tables:

int numberOfEntites = 1000;
var entities = new List<Item>();
var subEntities = new List<ItemHistory>();
for (int i = 1; i <= numberOfEntites; i++)
{
    var entity = new Item { Name = $"Name {i}" };
    entity.ItemHistories = new List<ItemHistory>()
    {
        new ItemHistory { Remark = $"Info {i}.1" },
        new ItemHistory { Remark = $"Info {i}.2" }
    };
    entities.Add(entity);
}

// Option 1
using (var transaction = context.Database.BeginTransaction())
{
    context.BulkInsert(entities, new BulkConfig { SetOutputIdentity = true });
    foreach (var entity in entities) {
        foreach (var subEntity in entity.ItemHistories) {
            subEntity.ItemId = entity.ItemId; // sets FK to match its linked PK that was generated in DB
        }
        subEntities.AddRange(entity.ItemHistories);
    }
    context.BulkInsert(subEntities);
    transaction.Commit();
}

// Option 2 using Graph (only for SQL Server)
// - all entities in relationship with main ones in list are BulkInsertUpdated
context.BulkInsert(entities, b => b.IncludeGraph = true);
  
// Option 3 with BulkSaveChanges() - uses ChangeTracker so little slower then direct Bulk
context.Items.AddRange(entities);
context.BulkSaveChanges();

When CalculateStats set to True the result returned in BulkConfig.StatsInfo (StatsNumber-Inserted/Updated/Deleted).<br> If used for pure Insert (with Batching) then SetOutputIdentity should also be configured because Merge is required.<br> TrackingEntities can be set to True if we want to have tracking of entities from BulkRead or if SetOutputIdentity is set.<br> UseTempDB when set then BulkOperation has to be inside Transaction.<br> UniqueTableNameTempDb when changed to false temp table name will be only 'Temp' without random numbers.<br> CustomDestinationTableName can be set with 'TableName' only or with 'Schema.TableName'.<br> CustomSourceTableName when set enables source data from specified table already in Db, so input list not used and can be empty.<br> CustomSourceDestinationMappingColumns dict can be set only if CustomSourceTableName is configured and it is used for specifying Source-Destination column names when they are not the same. Example in test DestinationAndSourceTableNameTest.<br> EnableShadowProperties to add (normal) Shadow Property and persist value. Disables automatic discriminator, use manual method.<br> IncludeGraph when set all entities that have relations with main ones from the list are also merged into theirs tables.<br> OmitClauseExistsExcept removes the clause from Merge statement, required when having noncomparable types like XML, and useful when need to active triggers even for same data.<br> _ Also in some sql collation small and capital letters are considered same (case-insensitive) so for BulkUpdate set it false.<br> DoNotUpdateIfTimeStampChanged if set checks TimeStamp for Concurrency, ones with conflict will not be updated.<br> SRID Spatial Reference Identifier - for SQL Server with NetTopologySuite.<br> DateTime2PrecisionForceRound If dbtype datetime2 has precision less then default 7, example 'datetime2(3)' SqlBulkCopy does Floor instead of Round so when this Property is set then Rounding will be done in memory to make sure inserted values are same as with regular SaveChanges.<br> TemporalColumns are shadow columns used for Temporal table. Default elements 'PeriodStart' and 'PeriodEnd' can be changed if those columns have custom names.<br> OnSaveChangesSetFK is used only for BulkSaveChanges. When multiply entries have FK relationship which is Db generated, this set proper value after reading parent PK from Db. IF PK are generated in memory like are some Guid then this can be set to false for better efficiency.<br> ReplaceReadEntities when set to True result of BulkRead operation will be provided using replace instead of update. Entities list parameter of BulkRead method will be repopulated with obtained data.

SqlBulkCopyOptions is Enum (only for SqlServer) with [Flags] attribute which enables specifying one or more options:<br> Default, KeepIdentity, CheckConstraints, TableLock, KeepNulls, FireTriggers, UseInternalTransaction<br> If need to set Identity PK in memory, Not let DB do the autoincrement, then need to use KeepIdentity:<br> var bulkConfig = new BulkConfig { SqlBulkCopyOptions = SqlBulkCopyOptions.KeepIdentity };<br> Useful for example when copying from one Db to another.

SetSynchronizeFilter<T> A method that receives and sets expresion filter on entities to delete when using BulkInsertOrUpdateOrDelete.<br> OnConflictUpdateWhereSql<T> To define conditional updates on merges, receives (existingTable, insertedTable).<br> --Example: bc.OnConflictUpdateWhereSql = (ex, in) => $"{in}.TimeUpdated > {ex}.TimeUpdated";<br> Last optional argument is Action progress (Example in EfOperationTest.cs RunInsert() with WriteProgress()).

context.BulkInsert(entitiesList, null, (a) => WriteProgress(a));

Library supports Global Query Filters and Value Conversions as well.</br> Additionally BatchUpdate and named Property works with EnumToString Conversion.</br> It can map OwnedTypes, also next are links with info how to achieve NestedOwnedTypes and OwnedInSeparateTable.</br> Table splitting are somewhat specific but could be configured in way Set TableSplit.</br> With Computed and Timestamp Columns it will work in a way that they are automatically excluded from Insert. And when combined with SetOutputIdentity they will be Selected.<br> Spatial types, like Geometry, also supported and if Entity has one, clause EXIST ... EXCEPT is skipped because it's not comparable.<br> Performance for bulk ops measured with ActivitySources named: 'BulkExecute' (tags: 'operationType', 'entitiesCount')<br> Bulk Extension methods can be Overridden if required, for example to set AuditInfo.<br> If having problems with Deadlock there is useful info in issue/46.

TPH inheritance

When having TPH (Table-Per-Hierarchy) inheritance model it can be set in 2 ways.<br> First is automatically by Convention in which case Discriminator column is not directly in Entity but is Shadow Property.<br> And second is to explicitly define Discriminator property in Entity and configure it with .HasDiscriminator().<br> Important remark regarding the first case is that since we can not set directly Discriminator to certain value we need first to add list of entities to DbSet where it will be set and after that we can call Bulk operation. Note that SaveChanges are not called and we could optionally turn off TrackingChanges for performance. Example:

public class Student : Person { ... }
context.Students.AddRange(entities); // adding to Context so that Shadow property 'Discriminator' gets set
context.BulkInsert(entities);

TPT (Table-Per-Type) as of v5 is partially supported.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.17.0 6,417 6/13/2024
8.16.2 3,221 5/22/2024
8.16.1 4,080 3/23/2024
8.16.0 35,691 2/17/2024
8.15.0 103 2/17/2024
8.14.0-preview1 2,426 12/17/2023
8.13.0-preview1 13,591 10/22/2023
8.12.0-preview1 74 10/18/2023
8.11.0-preview1 79 10/15/2023
8.10.0-preview1 71 10/10/2023
8.6.9-preview1 67 10/10/2023
8.6.8-preview1 68 10/10/2023
8.6.7-preview1 66 10/10/2023
8.6.6-preview1 73 10/10/2023
8.6.5-preview1 81 10/8/2023
7.17.0 416 6/13/2024
7.16.2 53 5/22/2024
7.16.1 166 3/23/2024
7.16.0 5,210 2/17/2024
7.15.0 97 2/17/2024
7.14.0 14,522 12/17/2023
7.13.0 3,606 10/22/2023
7.12.0 134 10/18/2023
7.11.0 122 10/15/2023
7.10.0 142 10/10/2023
7.6.9 115 10/10/2023
7.6.8 131 10/10/2023
7.6.7 131 10/10/2023
7.6.6 115 10/10/2023
7.6.5 162 10/8/2023
6.17.0 210 6/13/2024
6.16.2 55 5/22/2024
6.16.1 188 3/23/2024
6.16.0 128 2/17/2024
6.15.0 98 2/17/2024
6.14.0 120 12/17/2023
6.13.0 1,602 10/22/2023
6.12.0 125 10/18/2023
6.11.0 118 10/15/2023
6.10.0 126 10/10/2023
6.6.9 131 10/10/2023
6.6.8 142 10/10/2023
6.6.7 129 10/10/2023
6.6.6 111 10/10/2023
6.6.5 153 10/8/2023