Repository navigation
Bulk Update
Allows bulk-update of entities.
Enable bulk-update support by using the extension method AddBulkOperationSupport.
If you are using Lazy Loading then disable the registration of temp tables for primites types
sqlOptions.AddBulkOperationSupport(configureTempTablesForPrimitiveTypes: false).
var services = new ServiceCollection()
.AddDbContext<DemoDbContext>(builder => builder
// SQL Server
.UseSqlServer("conn-string", sqlOptions =>
{
sqlOptions.AddBulkOperationSupport();
})
// PostgreSQL
//.UseNpgsql("conn-string", npgsqlOptions =>
// {
// npgsqlOptions.AddBulkOperationSupport();
// })
// MySQL
//.UseMySql("conn-string", serverVersion, mySqlOptions =>
// {
// mySqlOptions.AddBulkOperationSupport();
// })
// SQLite
//.UseSqlite("conn-string", sqliteOptions =>
// {
// sqliteOptions.AddBulkOperationSupport();
// })Use one of the method overloads of BulkUpdateAsync to bulk-update entities.
By default, the columns of the primary key are used to perform the match.
List<Customer> customersToUpdate = ...;
// update entities as a whole
await ctx.BulkUpdateAsync(customersToUpdate);
// only "FirstName" has to be sent to the DB
// alternative ways to specify the column(s):
// * c => c.FirstName
// * c => new { c.FirstName}
// * new SqlServerBulkUpdateOptions{ PropertiesToUpdate = IEntityPropertiesProvider.Include<Customer>(c => c.FirstName) }
await ctx.BulkUpdateAsync(customersToUpdate, c => new { c.Id });
// use "propertiesToMatchOn" to specify the key properties to perform the JOIN on
await ctx.BulkUpdateAsync(new[] { customer },
propertiesToUpdate: c => c.FirstName,
propertiesToMatchOn: c => c.Id);Use the corresponding implementation of IBulkUpdateOptions to configure the update of entities.
- SQL Server:
SqlServerBulkUpdateOptions - PostgreSQL:
NpgsqlBulkUpdateOptions - MySQL:
MySqlBulkUpdateOptions - SQLite:
SqliteBulkUpdateOptions
By default, all properties of an entity are going to be updated. Use the options to specify the columns to update and the columns to match on.
var options = new SqlServerBulkUpdateOptions
{
KeyProperties = IEntityPropertiesProvider.Include<Customer>(c => c.Id),
PropertiesToUpdate = IEntityPropertiesProvider.Include<Customer>(c => c.FirstName)
// use "IEntityPropertiesProvider.Exclude" to exclude properties
};
await ctx.BulkUpdateAsync(customersToInsert, options);By default, the target table name and schema are resolved from the EF Core model. TableNameProvider overrides them per operation. The provider is called for the root entity type and for every owned entity type that is mapped to a separate table and takes part in the operation, nested owned types included.
Use IBulkOperationTableNameProvider.ForRootEntity(tableName, schema) when the entity has no owned types in separate tables:
// SQL Server
var options = new SqlServerBulkUpdateOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};
// PostgreSQL
var options = new NpgsqlBulkUpdateOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};
// MySQL (no schemas, see below)
var options = new MySqlBulkUpdateOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};
// SQLite
var options = new SqliteBulkUpdateOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};
await ctx.BulkUpdateAsync(customersToUpdate, options);schema == null means that no schema is emitted, so the database uses its default schema. It does not mean the schema of the EF Core model. IBulkOperationTableNameProvider.Default resolves the table name and the schema from the EF Core model. TableNameProvider defaults to this provider.
MySQL has no schemas. With the provider default SchemaBehavior MySqlSchemaBehavior.Throw, the operation throws a NotSupportedException before the first statement when the resolved table has a schema, also when the schema comes from the EF Core model. Set SchemaBehavior in UseMySql to MySqlSchemaBehavior.Ignore or MySqlSchemaBehavior.Translate, or remove the schema.
ForRootEntityWithDefaultSchema(tableName) uses the given table name and keeps the schema of the EF Core model (ToTable(name, schema) or HasDefaultSchema). ForRootEntityWithDefaultName(schema) keeps the table name of the EF Core model and uses the given schema. A null schema means that no schema is emitted. Both factories throw for owned types in separate tables in the same way as ForRootEntity. Both factories throw for temp table entities (ConfigureTempTableEntity), because they have no regular table: a temp table entity has no model table name for ForRootEntityWithDefaultName and no defined model schema for ForRootEntityWithDefaultSchema. Use ForRootEntity(tableName, schema) for them.
// given table name, schema of the model
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntityWithDefaultSchema("ArchiveCustomers")
// table name of the model, given schema
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntityWithDefaultName("archive")Note: Column resolution still uses the EF Core model. The target table must have compatible columns.
SQLite bulk update writes owned types that are mapped to their own table (OwnsOne(...).ToTable(...), OwnsMany(...)) to separate tables. ForRootEntity throws an InvalidOperationException when the operation reaches such an owned type. Without a transaction of the caller, SQLite rolls back the rows that were written before. Inside a transaction of the caller, these rows stay until the caller rolls back. Use IBulkOperationTableNameProvider.Create or implement IBulkOperationTableNameProvider to redirect the tables of the entity and of its owned types.
Create builds a provider from a delegate. The delegate is called for the root entity type and for every owned entity type that is mapped to a separate table. This example appends _Archive to the table name of the model:
var options = new SqliteBulkUpdateOptions { TableNameProvider = IBulkOperationTableNameProvider.Create(t => new BulkOperationTableName(IBulkOperationTableNameProvider.Default.GetTableName(t).Name + "_Archive")) };
await ctx.BulkUpdateAsync(customersToUpdate, options);The example emits no schema. Pass t.GetSchema() as the second argument of BulkOperationTableName to keep the schema of the model.
Implement the interface when the rule needs more than one expression:
public sealed class ArchiveTableNameProvider : IBulkOperationTableNameProvider
{
public BulkOperationTableName GetTableName(IEntityType entityType)
{
// The root entity type has no ownership. Owned entity types are distinct per navigation,
// even when two navigations use the same CLR type, so distinguish them by the owning navigation
// (or by entityType.Name), never by entityType.ClrType.
var ownership = entityType.FindOwnership();
var tableName = ownership is null ? "ArchiveCustomers" : "ArchiveCustomers_" + ownership.PrincipalToDependent!.Name;
// Schema == null means "no schema" (database default). Use entityType.GetSchema() to keep the schema of the model.
return new BulkOperationTableName(tableName);
}
}
var options = new SqliteBulkUpdateOptions { TableNameProvider = new ArchiveTableNameProvider() };
await ctx.BulkUpdateAsync(customersToUpdate, options);- The options
TableNameandSchemaare obsolete. They override the table of the root entity only, and a part that isnullkeeps the value of the EF Core model. They throw when the operation reaches an owned type in a separate table. SettingTableNameorSchemareplacesTableNameProvider, and settingTableNameProviderclearsTableNameandSchema. The last assignment wins. ReplaceTableName = "X"byForRootEntityWithDefaultSchema("X"),Schema = "s"byForRootEntityWithDefaultName("s"), and both options together byForRootEntity("X", "s"). These replacements keep the behavior of the options, with one exception:TableNamealone on a temp table entity uses the schema that the EF Core model returns for it (entityType.GetSchema()), butForRootEntityWithDefaultSchemathrows for it. UseForRootEntity(tableName, schema)for temp table entities.ForRootEntity("X")drops the schema of the EF Core model. - SQLite runs the whole operation, including the owned tables, in its own transaction when the
DbContexthas no current transaction, and an error rolls this transaction back. Inside a transaction of the caller, the written rows stay until the caller rolls back. - SQL Server, PostgreSQL and MySQL bulk update do not support owned types, see Owned Entity Types. Therefore
TableNameProvideris called for the root entity type only.
The bulk update is implemented via MERGE command on SQL Server. The table hints can be configured via MergeTableHints.
PostgreSQL uses a temp table with
UPDATE ... FROMinstead of MERGE.
var options = new SqlServerBulkUpdateOptions
{
// HoldLock is in the list by default
MergeTableHints = { SqlServerTableHintLimited.RowLock }
};MergeTableHints contains SqlServerTableHintLimited.HoldLock by default, see SQL Server: MERGE statement, result and limits.
The bulk update runs the MERGE of the upsert without the WHEN NOT MATCHED branch. The rules for NULL keys, for duplicate keys that match existing rows and for the transaction of the DbContext in SQL Server: MERGE statement, result and limits apply to the bulk update as well.
The bulk update is implemented via MERGE command. The entities are inserted into a temp table before MERGE. The creation of the temp table and the bulk insert of entities into temp table can be controlled via TempTableOptions.
var options = new SqlServerBulkUpdateOptions
{
TempTableOptions =
{
BatchSize = 5_000,
EnableStreaming = true,
BulkCopyTimeout = TimeSpan.FromSeconds(5)
}
};The default of TempTableOptions.SqlBulkCopyOptions is SqlBulkCopyOptions.KeepIdentity. Since 10.6.0 and 11.0.0, the library always adds SqlBulkCopyOptions.KeepIdentity to this value. Therefore the temp table keeps the key values of the entities, also when you set other flags, for example SqlBulkCopyOptions.TableLock. An older version uses the value as it is. The prerelease versions up to 10.6.0-beta05 and 11.0.0-beta03 use the value as it is as well. With such a version, keep the flag (SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.TableLock), because without it SQL Server generates new values for a key column that is an identity column (for example an int key by convention, or UseIdentityColumn()), and the MERGE then matches other rows or no rows.
MySQL stages the entities in a temporary table and updates the target with one statement:
CREATE TEMPORARY TABLE `Customers_1` (`__ord` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, UNIQUE (`Id`))
SELECT `Id`, `FirstName` FROM `Customers` LIMIT 0;
-- the rows are inserted with the registered insert path (multi-row INSERT or MySqlBulkCopy)
UPDATE /*+ SET_VAR(sql_safe_updates = 0) */ `Customers` AS d INNER JOIN `Customers_1` AS s ON d.`Id` = s.`Id` SET d.`FirstName` = s.`FirstName`;
DROP TEMPORARY TABLE IF EXISTS `Customers_1`;- The staging table copies type, charset, collation and NOT NULL of the target columns, so the values are converted and the keys are compared in the same way as in the target table. The column
__ordis the primary key, because the server settingsql_require_primary_key=ONdemands a primary key also for temporary tables. - The
UPDATE(and theDELETEof the upsert) carries the hint/*+ SET_VAR(sql_safe_updates = 0) */, because MySQL rejects these statements with error 1175 when the session usessql_safe_updates=ON. MySQL supports this hint from version 8.0.3 on. MariaDB and older MySQL versions do not support it, so there the statements can fail with error 1175 whensql_safe_updatesisON. This case is not tested. - The insert path of the registration fills the staging table, see MySQL-specific options.
MySqlBulkUpdateOptions.MaxParametersPerStatementandCommandTimeoutapply to the operation. - The return value is the number of matched rows, also of rows whose values do not change. The MySQL provider always uses
UseAffectedRows=False, so this rule holds for every connection. - The operation throws an
ArgumentExceptionwhen no column besides the key columns is left to update. - Without a transaction of the caller, the operation runs in its own transaction.
Duplicate keys in the input:
- The index
UNIQUE (keys)rejects two entities with the same key with error 1062. - The index does not detect duplicates when a key column is NULL (NULL values are distinct in a unique index) or when a key column has a TEXT, BLOB or JSON type (MySQL cannot index such a column without a prefix length, so the staging table has no key index). For such duplicates, MySQL updates the target row only once and counts it once in the return value. The row gets the values of one of the duplicates. MySQL does not document which one. In a probe with MySQL 8.4 it was the first duplicate in the input order, but do not rely on this order.
- With
useBulkCopy: true, a duplicate key raises aMySqlException"... only n was inserted" or "... only n were inserted" instead of error 1062. - A key that is wider than 3,072 bytes fails with error 1071 from the key index.
XA transactions: inside a TransactionScope with UseXaTransactions=true (the default of MySqlConnector), MySQL rejects CREATE TEMPORARY TABLE with error 4091 as long as the server setting xa_detach_on_prepare is ON (the default). The operation throws a NotSupportedException with the MySqlException as inner exception. Use one of these alternatives:
- Set
UseXaTransactions=falsein the connection string. - Use a transaction of the
DbContext(ctx.Database.BeginTransactionAsync()) instead of aTransactionScope. - Set
xa_detach_on_prepare=OFFon the server.
Other limits:
- By default, the name of the staging table is the temp table name of the entity (
<table>_<n>). When the override table (TableNameProvider) or a table of the EF Core model has exactly this name, the operation throws aNotSupportedExceptionbefore the first statement of the operation. For example, a model with the tablesOrdersandOrders_1cannot updateOrderswith the default name. A very long table name can fail with error 1059. In these cases, set another name withTempTableOptions.TableNameProvider, as described in MySQL: name of the staging table. - A default expression of a staged column that references a column that is not part of the operation fails with error 1054.
- When a table with the name of the staging table already exists on the connection, for example a temp table with
DropTableOnDispose = false, theCREATEfails with error 1050. The operation does not drop the existing table, because that table does not belong to the operation. - The library is not tested with MariaDB, with MySQL versions below 8.0.19, with GTID together with statement-based binary logging, and with bulk copy into a table without insertable columns.
By default, the staging table gets the temp table name of the entity (<table>_<n>), which ReusingTempTableNameProvider derives from the table name of the entity in the EF Core model. TableNameProvider of the options changes only the target table, not the staging table. Set TempTableOptions.TableNameProvider to an ITempTableNameProvider when the derived name cannot be used, for example when the table name of the model contains a placeholder that is replaced for the target table only, or when the derived name is too long.
The library has no provider for a fixed name, so implement ITempTableNameProvider:
using Microsoft.EntityFrameworkCore.Metadata;
using Thinktecture.EntityFrameworkCore.TempTables;
public sealed class StagingTableNameProvider(string name) : ITempTableNameProvider
{
public ITempTableNameLease LeaseName(DbContext ctx, IEntityType entityType) => new Lease(name);
private sealed record Lease(string Name) : ITempTableNameLease
{
public void Dispose()
{
}
}
}var options = new MySqlBulkUpdateOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("Customers_2026"),
TempTableOptions =
{
TableNameProvider = new StagingTableNameProvider("Customers_staging")
}
};
await ctx.BulkUpdateAsync(customersToUpdate, options);MySqlBulkInsertOrUpdateOptions has the same TempTableOptions. The copy constructors of both options copy the provider. The operation disposes the lease of the name after the staging table is dropped.
Rules for the name:
- The name must be neither the name of the target table nor the name of a table of the EF Core model, because a MySQL temporary table hides the table with the same name for the connection. The operation throws a
NotSupportedExceptionfor such a name before the first statement of the operation. The comparison ignores case, so a name that differs only in case is rejected as well. - Use a stable name. Every new name produces a new
INSERTstatement, and the statement of a full batch stays prepared on the connection, see MySQL-specific options. A provider that returns a new name for every call (for example a name with a GUID) can reach the server limitmax_prepared_stmt_counton a connection that stays open (error 1461). - When a table with the same name already exists on the connection, the
CREATEfails with error 1050, see the limits above.
Bulk update supports entity types that are mapped with table-per-hierarchy (TPH). A collection that is typed as the base type can contain instances of all types of the hierarchy. The entities do not need to be attached to the DbContext. The page Entity Inheritance (TPH) gives an overview of all operations that support inheritance.
// "Circle" and "Rectangle" derive from "Shape"
List<Shape> shapes =
[
new Circle { Id = circleId, Name = "c1", Radius = 5 },
new Rectangle { Id = rectangleId, Name = "r1", Width = 6, Height = 7 }
];
// updates the columns of all types of the hierarchy, but not the discriminator
await ctx.BulkUpdateAsync(shapes);
// a member of a derived type is selected through a cast
await ctx.BulkUpdateAsync(shapes, propertiesToUpdate: s => new { s.Name, ((Circle)s).Radius });The following rules apply:
-
Columns: A full update sets all columns of the type of the collection, of its base types and of its derived types, except the key columns and the discriminator. A partial update (
PropertiesToUpdate) sets the selected columns only. In both cases, a column that the type of a row does not have is set toNULL. Two sibling types can map a property to the same column. Such a shared column is set once, and every row writes the property of its own type. -
Type of a row: The type of every entity is resolved by the rule of
SaveChanges. It is the entity type of the CLR type, or of the nearest CLR base class that is mapped. -
Discriminator: The discriminator is never updated, because EF Core treats it as read-only after the row was saved.
PropertiesToUpdatethat includes a CLR discriminator property throws anInvalidOperationException("... is the discriminator. It is read-only after it has been saved ...").Excludeof a CLR discriminator property has no effect. - Type mismatch: The library does not check the type of the existing row. When an entity has another type than the existing row with the same key, the discriminator keeps the old type, and the columns are written as described above. The caller is responsible for passing entities of the type of the existing rows.
-
Selecting columns:
IEntityPropertiesProvider.IncludeandIEntityPropertiesProvider.Excludeaccept a member of a derived type through a cast, for examples => ((Circle)s).Radius. Theasoperator works as well, and the cast can be used inside an anonymous object. A member of one sibling type selects the shared column for all rows. A member inKeyProperties(propertiesToMatchOn) must be declared on the type of the collection or on one of its base types. Such a member also works through a cast to a derived type, for examples => ((Circle)s).Id. A member that is declared on a derived type throws aNotSupportedException("... cannot be used as a key property ..."). A cast member that the entity type itself does not have throws aNotSupportedExceptionwhen the entity type has no discriminator. A cast to an unmapped subclass selects the member of the nearest mapped base type of the subclass. When that base type is not an entity type of the hierarchy, the selection throws anInvalidOperationException("... is not an entity type of the hierarchy of ..."). -
Invalid rows: An entity whose type is not a concrete type of the collection type throws an
InvalidOperationException. The type is checked while the rows are sent. SQL Server, PostgreSQL and MySQL send all rows into a temp table first. Therefore the target table is unchanged when a row is invalid. SQLite updates the target rows one after another, so the rows before the invalid row are already written. When the operation runs in its own transaction, SQLite rolls them back. A transaction of the caller keeps them until the caller rolls it back. -
Owned types: The owned types of the base types of the collection type belong to the operation. Therefore an update through a derived type with an owned type on a base type throws a
NotSupportedExceptionon SQL Server, PostgreSQL and MySQL, as for every other owned type (see Owned Entity Types). SQL Server and PostgreSQL throw "Temp tables don't support owned entities." MySQL throws "MySQL bulk update and upsert do not support owned entities mapped to separate tables." for an owned type in a separate table and "Temp tables don't support owned entities." for an inlined owned type. SQLite updates these owned types. An owned type that is declared on a derived type throws aNotSupportedExceptionbefore the first statement on all providers. -
Shadow properties: A shadow property other than the discriminator is read through
ctx.Entry(entity)(see Shadow Properties). - Other inheritance mappings: Only TPH is supported. The bulk operations have no special handling and no check for table-per-type (TPT) and table-per-concrete-type (TPC) mappings. They handle such an entity type like an entity type without inheritance.
Required NuGet Package (one of):
Performs a server-side UPDATE ... FROM using an IQueryable<TSource> as the data source. This avoids materializing data client-side — the source can be a temp table query, a regular DbSet query, or any composable LINQ query.
The method joins the target table to the source subquery on specified key columns and applies property assignments defined via a fluent SetPropertyBuilder.
The API is the same across all four providers. Only the options class differs:
// Insert updated values into a temp table
var updatedCustomers = new List<Customer>
{
new() { Id = customerId1, FirstName = "Updated1", Score = 10 },
new() { Id = customerId2, FirstName = "Updated2", Score = 20 }
};
// SQL Server
await using var tempTable = await executor.BulkInsertIntoTempTableAsync(
updatedCustomers, new SqlServerTempTableBulkInsertOptions());
// PostgreSQL
// await using var tempTable = await executor.BulkInsertIntoTempTableAsync(
// updatedCustomers, new NpgsqlTempTableBulkInsertOptions());
// SQLite
// await using var tempTable = await executor.BulkInsertIntoTempTableAsync(
// updatedCustomers, new SqliteTempTableBulkInsertOptions());
// Update the target table from the temp table query
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
tempTable.Query, // IQueryable<Customer> source
target => target.Id, // target join key
source => source.Id, // source join key
builder => builder
.Set(e => e.FirstName, (e, f) => f.FirstName) // assign from source
.Set(e => e.Score, (e, f) => f.Score));The source can also be a regular DbSet query:
var sourceQuery = ctx.Set<Customer>().Where(c => c.IsActive);
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder.Set(e => e.Score, (e, f) => f.Score));Value selectors support constants, captured variables, static members (e.g. smart-enum values like Status.Published), and arithmetic expressions in addition to source/target property access. Every subtree of the value selector that does not depend on the lambda parameters is evaluated once on the client and rendered as a SQL literal with the type mapping of the target column. This includes a null-guarded conditional such as captured == null ? 0 : captured.Count and a method call on a captured value such as captured.Name.Trim(). Other expressions are translated to SQL by EF Core. Therefore the only SQL parameters of the UPDATE statement come from the source query. Values of types with a value converter on the target property (e.g. smart enums) are converted using that converter. This also holds for a client value inside an expression that EF Core translates, for example a branch of a conditional whose test uses a column: (e, f) => f.Count > 15 ? Status.Published : Status.Draft renders the converted values in the CASE expression. A conditional inside the source query (Select(x => new { Status = x.Count > 15 ? Status.Published : Status.Draft }) with .Set(e => e.Status, (e, f) => f.Status)) is translated as part of the source query and does not get the converter of the target column; write such a conditional in Set.
// Set a column to a constant value
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder
.Set(e => e.Score, (e, f) => 42) // constant
.Set(e => e.FirstName, (e, f) => f.FirstName)); // source property
// Set a column to a captured variable
var newStatus = "Archived";
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder
.Set(e => e.Status, (e, f) => newStatus) // captured variable
.Set(e => e.Score, (e, f) => f.Score)); // source property
// Arithmetic on source properties
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder
.Set(e => e.Score, (e, f) => f.Score + 10)); // source + constant
// Mixed target and source arithmetic
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder
.Set(e => e.Score, (e, f) => e.Score + f.Score)); // target + source
// Complex arithmetic
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder
.Set(e => e.Score, (e, f) => e.Score + f.Score * 2)); // target + source * 2Note: Value selectors support property access,
EF.Propertycalls, constants, captured variables, static members, arithmetic operators (+,-,*,/,%), and any expression EF Core can translate to SQL — including server-translatable method calls such asf.Name.ToUpper()orf.Name.Substring(0, 3). Only client-only expressions that EF Core cannot translate to SQL are not supported. A captured collection with a lambda (items.Select(i => i.Id),items.Where(i => i.Active).Count()) and a captured array (ids.Contains(f.Id)with anint[]) are evaluated on the client and are supported. Static members are evaluated once at translation time, except members EF Core translates server-side (e.g.DateTime.Now).
A subtree is evaluated on the client only when it does not use the lambda parameters e and f and when EF Core translates none of its members server-side (DateTime.Now stays server-side). A lambda inside the subtree is supported: (e, f) => items.Select(i => i.Id).Contains(f.Id) as the filter renders IN (...) with the ids as literals (a single id renders = ..., and an empty collection renders a false condition, so no row is updated), and .Set(e => e.Count, (e, f) => items.Where(i => i.Active).Count()) writes the count as a literal. An array works the same way: (e, f) => ids.Contains(f.Id) with an int[], Guid[] or string[] ids renders IN (...), and an array inside a captured lambda (items.Where(i => ids.Contains(i.Id)).Count()) is evaluated on the client together with the lambda, as is a.SequenceEqual(b) of two arrays. A collection with a null element (int?[] { 7, null }, List<int?>, string?[]) renders IN (...) OR ... IS NULL, and a collection that is null renders a false condition, so no row is updated; both follow the translation of EF Core for a collection parameter. With UseRelationalNulls the null element is dropped and only IN (...) is rendered, as in EF Core. A null collection in a subtree that is evaluated on the client (ids!.Contains(5)) throws the InvalidOperationException of the client evaluation, because Enumerable.Contains rejects a null source. C# 14 binds these calls for an array to the span methods of MemoryExtensions; the library rewrites them to Enumerable.Contains and Enumerable.SequenceEqual, as EF Core does for a query. A comparer argument (ids.Contains(f.Id, comparer)) cannot be translated to SQL and throws the translation error; in a client-evaluated subtree (ids.Contains(3, comparer)) the comparer is applied. A lambda that uses e or f, for example items.Where(i => i.Id == f.Id), cannot be evaluated on the client and throws the translation error of EF Core. The subtree is evaluated as a whole, so C# semantics hold: nullableInt.HasValue ? 1 : 2 with a null nullableInt writes 2, and captured == null ? 0 : captured.Count with a null captured writes 0. A member access on a captured null throws an ArgumentException ("The member '…' of '…' cannot be read because the captured value is null. ..."), in a value selector and in the filter. Any other exception during the client evaluation throws an InvalidOperationException that names the expression and keeps the original exception as inner exception. When the test of a conditional contains no lambda parameter, the test is evaluated on the client and only the selected branch is used. The operators && and || with such a left operand are evaluated in the same way. Therefore a null guard also protects an expression that reads a column: the filter (e, f) => captured == null || e.Name == captured.Name updates all rows for a null captured, and (e, f) => captured == null ? f.Count : captured.Count + f.Count writes the value of f.Count. EF.Functions methods are always translated to SQL. A captured query (IQueryable) is never executed during the translation, so a value selector such as (e, f) => dbContext.Set<Product>().Count() throws an InvalidOperationException.
A comparison with null in the source query, in filter and in a value expression follows the null semantics of EF Core. For example, s.Name == null is translated to IS NULL. A comparison with a captured variable whose value is null is translated in the same way. The option UseRelationalNulls is respected. A comparison between two nullable columns, for example e.Name == s.Name, treats two NULL values as equal, as in C#, unless UseRelationalNulls is set. The key selectors follow the join semantics of EF Core. A single key never matches when it is NULL. For a composite key, a part that is NULL on both sides matches, unless UseRelationalNulls is set.
The parameters of the source query are bound with the type mappings of EF Core. Therefore the source query can compare a property with a value converter to a captured value. It can be a FromSqlRaw or FromSql query with arguments. It can use a collection parameter in every translation mode, including the JSON parameter that SQL Server uses for EF.Parameter(list), for ParameterTranslationMode.Parameter and for more than about 2,100 elements.
On MySQL, a captured TimeSpan is written as TIME '[-]HH:mm:ss.ffffff' with the total hours (at least two digits) and always six fraction digits. Therefore a negative value and a value of 24 hours or more keep their value. MySQL rounds the fraction to the precision of the column, as it does for a parameter. MySQL rejects a value outside -838:59:59 to 838:59:59 with error 1525.
On MySQL, EF.Parameter(list) in the source query needs EnablePrimitiveCollectionsSupport() of the provider Microting.EntityFrameworkCore.MySql. Without it, the query fails with "... Primitive collections support has not been enabled.", also as a plain EF Core query. A captured list and a collection parameter work without this setting.
Since version 10.6.0, the target selector of Set can reach a member of a complex type that is mapped with ComplexProperty. The complex type can be a class or a struct, and complex types can be nested.
public readonly record struct TimestampPair(long ReceivedAt, long MessageTimestamp);
public class Message
{
public Guid Id { get; set; }
public long MessageTimestamp { get; set; }
public TimestampPair EffectiveMessage { get; set; }
public string? Name { get; set; }
}
modelBuilder.Entity<Message>(builder =>
{
builder.HasKey(e => new { e.Id, e.MessageTimestamp });
builder.ComplexProperty(e => e.EffectiveMessage, c =>
{
c.Property(p => p.ReceivedAt).HasColumnName("effective_received_at");
c.Property(p => p.MessageTimestamp).HasColumnName("effective_message_timestamp");
});
});Set single members of the complex property:
// PostgreSQL
await using var tempTable = await ctx.BulkInsertIntoTempTableAsync(
updatedMessages, new NpgsqlTempTableBulkInsertOptions());
var affectedRows = await ctx.Set<Message>().BulkUpdateAsync(
tempTable.Query,
e => new { e.Id, e.MessageTimestamp },
f => new { f.Id, f.MessageTimestamp },
builder => builder
.Set(e => e.EffectiveMessage.ReceivedAt, (e, f) => f.EffectiveMessage.ReceivedAt)
.Set(e => e.EffectiveMessage.MessageTimestamp, (e, f) => f.EffectiveMessage.MessageTimestamp));Set the whole complex property. The library expands this assignment into one SET assignment per member column, here effective_received_at and effective_message_timestamp. Nested complex types are expanded recursively. The value can be the complex property of the source, a captured variable, or a new expression without a lambda parameter, such as new TimestampPair(7, 8), which is evaluated once on the client:
// value from the source
builder => builder
.Set(e => e.EffectiveMessage, (e, f) => f.EffectiveMessage)
.Set(e => e.Name, (e, f) => f.Name)
// value from a captured variable
var effectiveMessage = new TimestampPair(7, 8);
builder => builder.Set(e => e.EffectiveMessage, (e, f) => effectiveMessage)Members with a value converter are supported. A captured value is converted with the value converter of the target column.
A whole complex property skips the members whose value the database generates, for example computed columns (GetBeforeSaveBehavior() == PropertySaveBehavior.Ignore). The other bulk operations use the same rule. Set such a member explicitly to write it. When every writable member of a whole complex property is generated, an ArgumentException is thrown for that property, also when other columns are set ("No column can be written, because every member of the selected complex properties is generated (PropertySaveBehavior.Ignore). Expression: ...").
The following cases are not supported:
- A complex collection (a collection of complex types) throws a
NotSupportedException("The complex collection '…' is not supported."). - A single member of a nullable complex property cannot be set, for a class (for example
e => e.OptionalBoundary!.Upper) as well as for a struct (for examplee => e.OptionalPair!.Value.ReceivedAt). It throws aNotSupportedException("The member '…' of '…' is a nullable complex property. ..."). The reason is a loss of data. EF Core reads a row whose complex property isNULLin the database asnull, or it reads the other required members as their default values. Therefore the value of the single member would be lost without an error. Set the whole nullable complex property instead, see Nullable complex properties. - A target selector that goes through a member that is not a complex property (for example a navigation) throws a
NotSupportedException("The member '…' is not a complex property of '…'. ..."). - A target selector that is not a member chain on the lambda parameter, for example
e => e.Count + 1or a method call, throws aNotSupportedException("Only simple property access expressions (e => e.Property), member access through complex properties (e => e.ComplexProperty.Property) or EF.Property calls on the lambda parameter are supported. ..."). -
EF.Propertyis supported only on the lambda parameter.EF.Propertythrough a complex property (for exampleEF.Property<long>(e.EffectiveMessage, "ReceivedAt")) throws aNotSupportedException("EF.Property is supported only on the lambda parameter, not through a complex property, a navigation or another expression. ..."). Use the member accesse.EffectiveMessage.ReceivedAtinstead. - A member that is not mapped throws an
InvalidOperationException("The property '…' is not a mapped property on '…'."). For a member of a complex type, the message names the complex type. - A captured
nullas the value of a whole required (non-nullable) complex property throws anArgumentException("The member '…' of '…' cannot be read because the captured value is null. ..."). Pass a non-null value, or set the members one by one. A captured variable of a nullable type, for exampleTimestampPair?, is accepted for a required struct complex property when it has a value, and it throws the same exception when it isnull. For a nullable complex property, a capturednullwritesNULLinto every member column. - Each target column can be set only once. A second assignment to the same column throws an
ArgumentException("The target column '…' is set more than once. ..."). This rule also applies when a whole complex property and one of its members are both set. Set either the whole complex property or its members. The rule applies to all providers.
EF Core cannot bind a nested complex type to a constructor parameter. Therefore the members of a nested complex type need a setter or an init accessor.
A nullable (optional) complex property can be set as a whole. The complex type can be a class or a struct. The library writes it in the same way as SaveChanges:
- A
nullvalue writesNULLinto every member column. - A non-null value writes the value of each member into its column.
- When the complex type is configured with
HasDiscriminator(), the library also writes the discriminator column. The column gets the discriminator value of the complex type for a non-null value andNULLfor anullvalue.
EF Core requires that an optional complex type in table columns has at least one required member or a discriminator that is configured with HasDiscriminator().
public class BoundaryValueObject
{
public int Upper { get; set; }
public int Lower { get; set; }
}
public class Product
{
public Guid Id { get; set; }
public BoundaryValueObject? OptionalBoundary { get; set; }
}
modelBuilder.Entity<Product>(builder => builder.ComplexProperty(e => e.OptionalBoundary));A value from the source copies the member columns as they are, without a CASE expression. A source row in which only some member columns are NULL is also copied without a change. The same copy applies when the source value is a nullable complex property and the target is a required complex property. For a source row whose complex property is NULL, the database rejects the NULL for a NOT NULL column. Example:
builder => builder.Set(e => e.OptionalBoundary, (e, s) => s.OptionalBoundary)A captured variable, a new expression or a captured collection with a lambda (boundaries.FirstOrDefault(b => b.Upper == 5)) is evaluated on the client once per member column, so the expression must return the same value on every call. When the value is null, every member column gets NULL:
BoundaryValueObject? boundary = null; // or a value
builder => builder.Set(e => e.OptionalBoundary, (e, s) => boundary)A conditional expression (?:) or a null-coalescing expression (??) can choose between complex values. When the condition uses only captured values, the selected branch is written. When the condition uses columns, every member column gets a CASE expression:
builder => builder.Set(e => e.OptionalBoundary, (e, s) => boundary ?? s.OptionalBoundary)
builder => builder.Set(e => e.OptionalBoundary, (e, s) => s.Count > 0 ? s.OptionalBoundary : e.OptionalBoundary)
builder => builder.Set(e => e.OptionalBoundary, (e, s) => s.OptionalBoundary ?? e.OptionalBoundary)A member access on such an expression, for example (boundary ?? s.Boundary).Lower as the value of the single member e.Boundary.Lower, is not supported. Write the conditional per member instead, for example boundary == null ? s.Boundary.Lower : boundary.Lower, or set the whole complex property.
Nesting is supported in both directions: a nullable complex property inside a required complex property, and a required complex property inside a nullable complex property. A null value on any level writes NULL into every column below that level.
The entity-based BulkUpdateAsync writes a nullable complex property in the same way. A required (non-nullable) complex property of a class type can be null on the entity. In this case, the library writes NULL into every member column, and the database rejects the value for a NOT NULL column. SaveChanges throws an exception in this case as well.
Use anonymous types to join on multiple columns:
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => new { e.Id, e.Region },
f => new { f.Id, f.Region },
builder => builder.Set(e => e.Score, (e, f) => f.Score));Keys are matched by position (first target key ↔ first source key). The number of target and source keys must be the same.
Use the optional filter parameter to restrict which target rows are updated.
The filter can reference both target and source properties:
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder.Set(e => e.Score, (e, f) => f.Score),
filter: (e, f) => e.Score < f.Score);Generated SQL (SQL Server):
UPDATE t SET [Score] = s.[Score]
FROM [Customers] AS t
INNER JOIN (<source>) AS s ON (t.[Id] = s.[Id])
WHERE t.[Score] < s.[Score];Generated SQL (PostgreSQL / SQLite):
UPDATE "Customers" AS t SET "Score" = s."Score"
FROM (<source>) AS s
WHERE t."Id" = s."Id" AND t."Score" < s."Score";The filter supports the same expression types as value selectors: property access,
constants, captured variables, arithmetic, and any expression EF Core can translate
to SQL — including server-translatable method calls such as f.Name.Contains("...").
Only client-only expressions that EF Core cannot translate are not supported.
Override the target table per operation with TableNameProvider on the provider-specific options class:
// SQL Server
var affectedRows = await ctx.Set<Customer>().BulkUpdateAsync(
sourceQuery,
e => e.Id,
f => f.Id,
builder => builder.Set(e => e.Score, (e, f) => f.Score),
new SqlServerBulkUpdateFromQueryOptions
{
TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
});
// PostgreSQL
// new NpgsqlBulkUpdateFromQueryOptions { TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive") }
// MySQL (no schemas, see Table override)
// new MySqlBulkUpdateFromQueryOptions { TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers") }
// SQLite
// new SqliteBulkUpdateFromQueryOptions { TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers") }TableNameProvider defaults to IBulkOperationTableNameProvider.Default, which resolves the table name and the schema from the EF Core model. The provider is called for the target entity type only. Only the target table is redirected. The source query keeps reading the tables of the EF Core model, also when it reads the model table of the target entity, for example when an archive table is filled from its model table. The target parameter of the filter and of the value expressions refers to the row of the override table. schema == null means that no schema is emitted, so the database uses its default schema. The options TableName and Schema are obsolete, see Table override.
SQL Server — uses UPDATE ... FROM ... INNER JOIN:
UPDATE t
SET
[FirstName] = s.[FirstName], [Score] = s.[Score]
FROM [Schema].[Customers] AS t
INNER JOIN (
SELECT [p].[Id], [p].[FirstName], [p].[Score]
FROM [#TempTable_1] AS [p]
) AS s ON (t.[Id] = s.[Id])
;PostgreSQL / SQLite — uses UPDATE ... FROM ... WHERE:
UPDATE "Schema"."Customers" AS t
SET
"FirstName" = s."FirstName", "Score" = s."Score"
FROM (
SELECT "p"."Id", "p"."FirstName", "p"."Score"
FROM "#TempTable_1" AS "p"
) AS s
WHERE t."Id" = s."Id"
;MySQL uses UPDATE ... INNER JOIN ... SET. The source is a table or a derived table, and the filter becomes a WHERE clause:
UPDATE `Customers` AS `t`
INNER JOIN `Customers_1` AS `t0` ON `t`.`Id` = `t0`.`Id`
SET `t`.`FirstName` = `t0`.`FirstName`, `t`.`Score` = `t0`.`Score`The MySQL statement does not use a staging table, so the XA limit of the entity-based bulk update does not apply. The return value is the number of matched rows.
On MySQL, a source query over the target table must not contain a subquery on the target table, for example ctx.Customers.Where(c => ctx.Customers.Any(o => o.Score > c.Score)). MySQL merges the source into the UPDATE statement and then rejects the statement with error 1093 ("You can't specify target table ... for update in FROM clause"). A source over the target table without such a subquery works.
Dependeding on the database you may hit some limitations when using default values. The limitations are applied to both the default values defined using HasDefaultValueSql and HasDefaultValue.
modelBuilder.Entity<Customer>(builder =>
{
builder.Property(e => e.StringProperyWithSqlDefaultValue).HasDefaultValueSql("'foo'");
builder.Property(e => e.StringPropertyWithDefaultValue).HasDefaultValue("bar");
});The Entity Framework Core is able to handle default values properly because every entity is handled individually. Generating individual SQL statements during bulk update would contradict the whole idea of this feature.
If an entity has shadow properties, the library reads their values through ctx.Entry(entity) of the DbContext that runs the operation. Set the values with ctx.Entry(entity).Property("Name").CurrentValue = value on that DbContext before the call. The entity does not have to be added or attached. See When the library reads the change tracker.
Owned entity types are supported by SQLite only:
| Owned type | SQL Server | PostgreSQL | MySQL | SQLite |
|---|---|---|---|---|
OwnsOne in the table of the owner (inlined) |
- | - | - | Y |
OwnsOne mapped to a separate table |
- | - | - | Y |
OwnsMany (always a separate table) |
- | - | - | Y |
- SQL Server and PostgreSQL throw a
NotSupportedException("Temp tables don't support owned entities.") for entities with owned types. The exception is thrown before the target table is written. - MySQL throws a
NotSupportedExceptionbefore the first statement: "MySQL bulk update and upsert do not support owned entities mapped to separate tables." for an entity with an owned type in a separate table, and "Temp tables don't support owned entities." when a property of an inlined owned type takes part in the operation. - SQLite updates the rows of owned types in separate tables by their primary key. The owned entities must be tracked by the
DbContext, for example because they were loaded together with the owner, so that the values of their shadow key properties can be read. - SQLite needs at least one column besides the key to update in the table of the root entity. If the root entity has no other column, for example an entity that consists of a key and of owned types in separate tables only, the update fails with a syntax error.
- Temp-Tables
- Bulk-Insert
- Bulk-Update
- Bulk-Upsert (Insert-or-Update)
- Entity Inheritance (TPH) (SQL Server, PostgreSQL, MySQL, SQLite)
- Truncate Tables