Skip to content

Bulk Insert

Pawel Gerr edited this page Dec 1, 2026 · 43 revisions

Required Nuget Package:
Thinktecture.EntityFrameworkCore.SqlServer
Thinktecture.EntityFrameworkCore.PostgreSQL
Thinktecture.EntityFrameworkCore.MySql
Thinktecture.EntityFrameworkCore.Sqlite

Allows bulk-insert of entities.

Enable bulk-insert support

Enable bulk-insert 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();
                               //                          })

Usage

Use one of the method overloads of BulkInsertAsync to bulk-insert entities. The method returns the number of inserted rows.

List<Customer> customersToInsert = ...;

// insert entities as a whole
int numberOfInsertedRows = await ctx.BulkInsertAsync(customersToInsert);

// only "Id" has to be sent to the DB
// alternative ways to specify the column(s):
// * c => new { c.Id }
// * c => c.Id
// * new SqlServerBulkInsertOptions { PropertiesToInsert = IEntityPropertiesProvider.Exclude<Customer>(c => new { c.Id })};
numberOfInsertedRows = await ctx.BulkInsertAsync(customersToInsert, c => new { c.Id });

Bulk Insert Options

Use the corresponding implementation of IBulkInsertOptions to configure the insert of the entities.

  • SQL Server: SqlServerBulkInsertOptions
  • PostgreSQL: NpgsqlBulkInsertOptions
  • MySQL: MySqlBulkInsertOptions
  • SQLite: SqliteBulkInsertOptions

Insert subset of properties only

By default, all properties of an entity are going to be inserted. You can use the options to specify the columns to insert.

var options = new SqlServerBulkInsertOptions
{
   PropertiesToInsert = IEntityPropertiesProvider.Include<Customer>(c => new { c.Id, c.FirstName, c.LastName }),
   // use "IEntityPropertiesProvider.Exclude" to exclude properties
};

await ctx.BulkInsertAsync(customersToInsert, options);

Table override

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 SqlServerBulkInsertOptions
{
   TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};

// PostgreSQL
var options = new NpgsqlBulkInsertOptions
{
   TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};

// MySQL (no schemas, see below)
var options = new MySqlBulkInsertOptions
{
   TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};

// SQLite
var options = new SqliteBulkInsertOptions
{
   TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};

await ctx.BulkInsertAsync(customersToInsert, 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, every MySQL bulk 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 (the schema is dropped) or MySqlSchemaBehavior.Translate (the translator maps the schema into the table name), 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.

Owned types in separate tables

Owned types that are mapped to their own table (OwnsOne(...).ToTable(...), OwnsMany(...)) are written to separate tables. ForRootEntity throws an InvalidOperationException when the operation reaches such an owned type. On SQL Server and PostgreSQL, rows of the root table may already be written at that point. SQLite rolls these rows back when the operation runs in its own transaction. MySQL resolves and validates the tables of the root and of every owned type in a separate table before the first write, so it writes no row in this case. 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 SqlServerBulkInsertOptions { TableNameProvider = IBulkOperationTableNameProvider.Create(t => new BulkOperationTableName(IBulkOperationTableNameProvider.Default.GetTableName(t).Name + "_Archive")) };
await ctx.BulkInsertAsync(customersToInsert, 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, "archive");
   }
}

var options = new SqlServerBulkInsertOptions { TableNameProvider = new ArchiveTableNameProvider() };
await ctx.BulkInsertAsync(customersToInsert, options);
  • The options TableName and Schema are obsolete. They override the table of the root entity only, and a part that is null keeps the value of the EF Core model. They throw when the operation reaches an owned type in a separate table. Setting TableName or Schema replaces TableNameProvider, and setting TableNameProvider clears TableName and Schema. The last assignment wins. Replace TableName = "X" by ForRootEntityWithDefaultSchema("X"), Schema = "s" by ForRootEntityWithDefaultName("s"), and both options together by ForRootEntity("X", "s"). These replacements keep the behavior of the options, with one exception: TableName alone on a temp table entity uses the schema that the EF Core model returns for it (entityType.GetSchema()), but ForRootEntityWithDefaultSchema throws for it. Use ForRootEntity(tableName, schema) for temp table entities. ForRootEntity("X") drops the schema of the EF Core model.
  • On SQL Server and PostgreSQL, the library does not wrap the writes of the root table and of the owned tables in a transaction. If the operation fails at an owned table after the root rows were written, the root rows stay in the table unless the caller started a transaction (ctx.Database.BeginTransactionAsync()). SQLite runs the whole operation, including the owned tables, in its own transaction when the DbContext has 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. MySQL starts its own transaction when the caller has none, see MySQL-specific options.

Typical SqlBulkCopy options (SQL Server)

var options = new SqlServerBulkInsertOptions
{
  BatchSize = 5_000,
  EnableStreaming = true,
  BulkCopyTimeout = TimeSpan.FromSeconds(5),
  SqlBulkCopyOptions = SqlBulkCopyOptions.Default
};

With the default SqlBulkCopyOptions.Default, SQL Server generates the value of an identity column and ignores the value of the entity. SqlBulkCopyOptions.KeepIdentity writes the value of the entity. The bulk operations return the number of rows and do not set generated values on the entities.

PostgreSQL-specific options

PostgreSQL uses the COPY command internally for maximum performance.

var options = new NpgsqlBulkInsertOptions
{
   // FREEZE option: rows are frozen immediately, bypassing MVCC visibility checks.
   // Significantly improves performance for bulk loads into newly created/truncated tables.
   Freeze = true,

   CommandTimeout = TimeSpan.FromSeconds(60),

   PropertiesToInsert = IEntityPropertiesProvider.Include<Customer>(c => new { c.Id, c.FirstName, c.LastName })
};

await ctx.BulkInsertAsync(customersToInsert, options);

MySQL-specific options

The registration decides how MySQL inserts the rows. This choice applies to every insert of the bulk operations: bulk insert, temp tables, and the staging tables of bulk update and bulk upsert.

.UseMySql("conn-string", serverVersion, mySqlOptions =>
{
   mySqlOptions.AddBulkOperationSupport(
      useBulkCopy: false,                 // default: multi-row INSERT statements
      maxParametersPerStatement: 5_000);  // default: 5,000 parameters per INSERT statement
});

Multi-row INSERT (default). The executor sends INSERT INTO ... VALUES (...), (...), ... statements with parameters. The number of rows per statement is maxParametersPerStatement divided by the number of columns, and at least 1. The value must be between 1 and 65,535 (the limit of a prepared statement), otherwise AddBulkOperationSupport throws an ArgumentOutOfRangeException. The statement of a full batch is prepared once and executed for every full batch with new values. The last partial batch runs as a normal statement.

MySqlConnector keeps a prepared statement on the connection until the connection is reset or closed. With ConnectionReset=true (the default), MySqlConnector releases the statements when the pooled connection is opened again. An idle connection in the pool keeps its statements until then or until it is closed. On a connection that stays open for a long time, or with ConnectionReset=false, many bulk inserts into tables with different names can reach the server limit max_prepared_stmt_count (16,382 by default, error 1461).

The options of one operation can override the value of the registration:

var options = new MySqlBulkInsertOptions
{
   MaxParametersPerStatement = 10_000,
   CommandTimeout = TimeSpan.FromSeconds(60)
};

await ctx.BulkInsertAsync(customersToInsert, options);

MaxParametersPerStatement exists on MySqlBulkInsertOptions, MySqlTempTableBulkInsertOptions, MySqlBulkUpdateOptions and MySqlBulkInsertOrUpdateOptions. With bulk copy the option has no effect.

Bulk copy. AddBulkOperationSupport(useBulkCopy: true) uses MySqlBulkCopy (LOAD DATA LOCAL INFILE). The rows are streamed to the server; they are not buffered in memory.

  • The connection string needs AllowLoadLocalInfile=true, otherwise the operation throws a NotSupportedException before it sends data. The server needs local_infile=ON, which is OFF by default.
  • LOAD DATA LOCAL turns errors into warnings and drops or changes the affected rows. Therefore the operation throws an InvalidOperationException ("MySqlBulkCopy inserted n of m rows. ...") for every warning of the level Warning or Error and when the number of inserted rows differs from the number of read rows. Inside a transaction of the caller, the rows that MySQL inserted before the error stay in that transaction until the caller rolls it back. Without a transaction of the caller, the library rolls back its own transaction. A warning of the level Note, for example the rounding of a decimal to the scale of the column, is ignored, because the INSERT path accepts the same value.
  • A duplicate key raises a MySqlException with the message "... only n was inserted" or "... only n were inserted", not error 1062.
  • An exception of the source collection during streaming (the enumeration, a property getter or a value converter) reaches the caller unchanged, and the connection and the transaction stay usable. The rows before the failing row are already loaded. Without a transaction of the caller, the library rolls back its own transaction. Inside a transaction of the caller, these rows stay in that transaction until the caller rolls it back.
  • A column of the type YEAR throws a NotSupportedException.
  • CommandTimeout limits the single LOAD DATA statement, that is the complete insert. On the default INSERT path it limits each statement.
  • When the server has local_infile=OFF, every call fails, and MySqlConnector keeps the data reader of the failed call, together with its entities, in memory until the process ends. The library cannot prevent this, because it can check only AllowLoadLocalInfile of the connection string. Enable local_infile on the server before you register bulk copy.

Transactions (MySQL). When the caller has no transaction, the MySQL bulk insert, bulk update and bulk upsert start their own transaction. When a statement fails, the library rolls back this transaction, so no row of the operation stays in the table. Inside a transaction of the caller, also inside an ambient TransactionScope, the operations use that transaction. A TransactionScope without TransactionOptions uses the isolation level Serializable, and MySqlConnector applies this level to the MySQL session, also for XA transactions. Therefore all statements inside such a scope run with SERIALIZABLE, which takes more locks. Pass new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted } or another level to the TransactionScope to select the level.

Packet size. The library does not estimate max_allowed_packet (64 MB by default). A statement that is larger fails with the error of MySqlConnector. Reduce MaxParametersPerStatement or raise max_allowed_packet in this case.

Table-per-hierarchy (TPH)

Bulk insert 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, and the collection is written in one pass. The page Entity Inheritance (TPH) gives an overview of all operations that support inheritance.

public class Shape
{
   public Guid Id { get; set; }
   public string Name { get; set; }
}

public class Circle : Shape
{
   public int Radius { get; set; }
}

public class Rectangle : Shape
{
   public int Width { get; set; }
   public int Height { get; set; }
}

List<Shape> shapes =
[
   new Circle { Id = Guid.NewGuid(), Name = "c1", Radius = 3 },
   new Rectangle { Id = Guid.NewGuid(), Name = "r1", Width = 4, Height = 5 }
];

// writes the columns of all types of the hierarchy and the discriminator
await ctx.BulkInsertAsync(shapes);

// a member of a derived type is selected through a cast
await ctx.BulkInsertAsync(shapes, s => new { s.Id, s.Name, ((Circle)s).Radius, ((Rectangle)s).Width, ((Rectangle)s).Height });

The following rules apply:

  • Columns: The default columns are the columns of the type of the collection, of its base types and of its derived types. Two sibling types can map a property to the same column. Such a shared column is written once, and every row writes the property of its own type. A column that the type of a row does not have gets NULL.
  • 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. Therefore an instance of an unmapped subclass is written as its nearest mapped type.
  • Discriminator: The discriminator is always written, also when PropertiesToInsert does not name it. Its value is the value that the model configures for the type of the row. The library never reads the value of a CLR discriminator property or of the change tracker. Therefore a wrong value in a CLR discriminator property is replaced with the value of the model. This rule is stricter than the rule of SaveChanges, which writes a value that is set.
  • Selecting columns: IEntityPropertiesProvider.Include and IEntityPropertiesProvider.Exclude accept a member of a derived type through a cast, for example s => ((Circle)s).Radius. The as operator 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. Exclude of a CLR discriminator property throws an InvalidOperationException. A cast member that the entity type itself does not have throws a NotSupportedException when the entity type has no discriminator. A cast to an unmapped subclass selects the member of the nearest mapped base type of the subclass. This is the same rule as for the type of a row. The same rule applies to a MemberInfo that is passed to IEntityPropertiesProvider.Include(IReadOnlyList<MemberInfo>) and whose ReflectedType is a subclass or a proxy type, also for an entity type without a discriminator. When the nearest mapped base type is not an entity type of the hierarchy, the selection throws an InvalidOperationException ("... is not an entity type of the hierarchy of ..."). A user-defined conversion and a cast to an unrelated type throw a NotSupportedException ("Complex projections are not supported.").
  • Invalid rows: An entity whose type is not a concrete type of the collection type throws an InvalidOperationException. Examples are an instance whose nearest mapped type is abstract, and an instance of a sibling type when the collection is typed as a type in the middle of the hierarchy. The type is checked while the rows are sent. Therefore an invalid row in the middle of the input fails after the earlier rows were sent. The atomicity is the same as for every other exception of the source, for example a property getter that throws. PostgreSQL aborts the COPY as a whole. When the operation runs in its own transaction, the transaction is rolled back. A transaction of the caller keeps the rows that were sent until the caller rolls it back. On SQL Server, SqlBulkCopy without a transaction keeps the batches that were sent.
  • Owned types: Owned types that are declared on the type of the collection or on one of its base types are written. An owned type that is declared on a derived type throws a NotSupportedException before the first row is written. When the type of the collection or one of its base types has an owned type, IEntityPropertiesProvider.Exclude throws a NotSupportedException ("The entity '...' must not contain owned entities."), as for an entity type without inheritance. IEntityPropertiesProvider.Include throws the same exception for the columns of a temp table (PropertiesToInclude) and for key properties.
  • Table: The root type of the hierarchy must be mapped to a table. Otherwise the operation throws an InvalidOperationException ("The entity type '...' is not mapped to a table.").
  • Shadow properties: A shadow property other than the discriminator is read through ctx.Entry(entity) (see Shadow Properties).
  • Custom data reader factory: A replaced IEntityDataReaderFactory must implement the overload Create<T>(DbContext, IEntityType, IEnumerable<T>, IReadOnlyList<PropertyWithNavigations>, bool). Otherwise a TPH entity type throws a NotSupportedException. Entity types without a discriminator work with the overload without IEntityType alone.
  • 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.

Bulk Insert from Query

Use BulkInsertAsync with an IQueryable<TSource> to insert rows from a server-side query without materializing data client-side. This generates INSERT INTO ... SELECT ... FROM (subquery).

Usage

// Insert from a temp table
await using var tempTable = await ctx.BulkInsertIntoTempTableAsync(sourceEntities, new SqlServerTempTableBulkInsertOptions());

var affectedRows = await ctx.Set<Customer>().BulkInsertAsync(
    tempTable.Query,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.Name, f => f.Name)
        .Map(e => e.Email, f => f.Email));

// Insert from a DbSet query
var sourceQuery = ctx.Set<Customer>()
                     .Where(c => c.IsActive)
                     .Select(c => new { c.Id, c.Name, c.Email });

var affectedRows = await ctx.Set<ArchivedCustomer>().BulkInsertAsync(
    sourceQuery,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.Name, f => f.Name)
        .Map(e => e.Email, f => f.Email));

Constants, variables, and expressions

Value selectors support constants, captured variables, static members (e.g. smart-enum values like Status.Published), and arithmetic expressions in addition to source property access. A value selector that is evaluated completely on the client is bound as an auto-generated SQL parameter (named __insert_const_0, __insert_const_1, etc.), for example a constant, a captured variable, a static member, captured == null ? 0 : captured.Count or a new expression. A constant inside a larger expression is rendered as a SQL literal. Every subtree of the value selector that does not depend on the lambda parameter is evaluated once on the client, for example a method call on a captured value such as captured.Name.Trim(). Other expressions are translated to SQL by EF Core. 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: 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 .Map(e => e.Status, 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 Map.

The same source column or expression can be mapped to several target columns, for example .Map(e => e.Count, f => f.Count).Map(e => e.Backup, f => f.Count). Every target column gets its own item in the SELECT list.

A source query with Distinct() keeps all of its distinct rows: the source is wrapped in a subquery (SELECT ... FROM (SELECT DISTINCT ...) AS t0), as EF Core does for a projection after Distinct().

// Map a column to a constant value
var affectedRows = await ctx.Set<Customer>().BulkInsertAsync(
    sourceQuery,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.Name, f => f.Name)
        .Map(e => e.Score, f => 42));             // constant

// Map a column to a captured variable
var defaultRegion = "EU";

var affectedRows = await ctx.Set<Customer>().BulkInsertAsync(
    sourceQuery,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.Name, f => f.Name)
        .Map(e => e.Region, f => defaultRegion));  // captured variable

// Arithmetic on source properties
var affectedRows = await ctx.Set<Customer>().BulkInsertAsync(
    sourceQuery,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.Name, f => f.Name)
        .Map(e => e.Score, f => f.Score * 2 + 1)); // arithmetic expression

Note: Value selectors support property access, EF.Property calls, constants, captured variables, static members, arithmetic operators (+, -, *, /, %), and any expression EF Core can translate to SQL — including server-translatable method calls such as f.Name.ToUpper() or f.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 an int[]) 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 parameter f and when EF Core translates none of its members server-side (DateTime.Now stays server-side). A lambda inside the subtree is supported: .Map(e => e.Count, f => items.Where(i => i.Active).Count()) is bound as __insert_const_N, and .Map(e => e.Count, f => items.Select(i => i.Id).Contains(f.Id) ? 1 : 0) renders CASE WHEN ... IN (...) (a single id renders =, and an empty collection renders a false condition). An array works the same way: .Map(e => e.Count, f => ids.Contains(f.Id) ? 1 : 0) with an int[], Guid[] or string[] ids renders CASE WHEN ... IN (...), and .Map(e => e.Count, f => items.Where(i => ids.Contains(i.Id)).Count()) is bound as __insert_const_N. C# 14 binds ids.Contains(x) for an array to the span method of MemoryExtensions; the library rewrites it to Enumerable.Contains, 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. 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 the value takes the else branch; 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. A lambda that uses f 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 inserts 2, and captured == null ? 0 : captured.Count with a null captured inserts 0. A member access on a captured null throws an ArgumentException ("The member '…' of '…' cannot be read because the captured value is null. ..."). 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, so a null guard also protects a branch that reads a column: f => captured == null ? f.Count : captured.Count + f.Count with a null captured inserts the value of f.Count. The operators && and || with such a left operand are evaluated in the same way. EF.Functions methods (e.g. EF.Functions.RowNumber(EF.Functions.OrderBy(1))) are always translated to SQL. A captured query (IQueryable) is never executed during the translation, so a value selector such as f => dbContext.Set<Product>().Count() throws an InvalidOperationException.

A comparison with null in the source query 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 value selector whose client value is null is rendered as the literal NULL instead of a parameter. A comparison between two nullable columns treats two NULL values as equal, as in C#, 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 that is rendered as a literal 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. A value selector that is a single captured TimeSpan is bound as a parameter.

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.

Complex types

Since version 10.6.0, the target selector of Map 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. The example uses the following entity:

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; }
}

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");
    });
});

Map single members, or map the whole complex property. The library expands a whole complex property into one column per member, 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.

// PostgreSQL
await using var tempTable = await ctx.BulkInsertIntoTempTableAsync(
    messages, new NpgsqlTempTableBulkInsertOptions());

// single members
var affectedRows = await ctx.Set<Message>().BulkInsertAsync(
    tempTable.Query,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.MessageTimestamp, f => f.MessageTimestamp)
        .Map(e => e.EffectiveMessage.ReceivedAt, f => f.EffectiveMessage.ReceivedAt)
        .Map(e => e.EffectiveMessage.MessageTimestamp, f => f.EffectiveMessage.MessageTimestamp));

// whole complex property
var affectedRows = await ctx.Set<Message>().BulkInsertAsync(
    tempTable.Query,
    builder => builder
        .Map(e => e.Id, f => f.Id)
        .Map(e => e.MessageTimestamp, f => f.MessageTimestamp)
        .Map(e => e.EffectiveMessage, f => 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. Map 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 mapped ("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 mapped, for a class (for example e => e.OptionalBoundary!.Upper) as well as for a struct (for example e => e.OptionalPair!.Value.ReceivedAt). It throws a NotSupportedException ("The member '…' of '…' is a nullable complex property. ..."). The reason is a loss of data. EF Core reads a row whose complex property is NULL in the database as null, or it reads the other required members as their default values. Therefore the value of the single member would be lost without an error. Map 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 + 1 or a method call, throws a NotSupportedException ("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.Property is supported only on the lambda parameter. EF.Property through a complex property (for example EF.Property<long>(e.EffectiveMessage, "ReceivedAt")) throws a NotSupportedException ("EF.Property is supported only on the lambda parameter, not through a complex property, a navigation or another expression. ..."). Use the member access e.EffectiveMessage.ReceivedAt instead.
  • 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 null as the value of a whole required (non-nullable) complex property throws an ArgumentException ("The member '…' of '…' cannot be read because the captured value is null. ..."). Pass a non-null value, or map the members one by one. A captured variable of a nullable type, for example TimestampPair?, is accepted for a required struct complex property when it has a value, and it throws the same exception when it is null. For a nullable complex property, a captured null writes NULL into every member column.
  • Each target column can be mapped only once. A second mapping to the same column throws an ArgumentException ("The target column '…' is mapped more than once. ..."). This rule also applies when a whole complex property and one of its members are both mapped. Map 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.

Nullable complex properties

A nullable (optional) complex property can be mapped as a whole. The complex type can be a class or a struct. The library writes it in the same way as SaveChanges:

  • A null value writes NULL into 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 and NULL for a null value.

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
    .Map(e => e.Id, s => s.Id)
    .Map(e => e.OptionalBoundary, 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
    .Map(e => e.Id, s => s.Id)
    .Map(e => e.OptionalBoundary, 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
    .Map(e => e.Id, s => s.Id)
    .Map(e => e.OptionalBoundary, s => boundary ?? s.OptionalBoundary)

builder => builder
    .Map(e => e.Id, s => s.Id)
    .Map(e => e.OptionalBoundary, s => s.Count > 0 ? s.OptionalBoundary : null)

builder => builder
    .Map(e => e.Id, s => s.Id)
    .Map(e => e.OptionalBoundary, s => s.OptionalBoundary ?? boundary)

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 map 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.

BulkInsertAsync with a collection of entities 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.

Table override

// SQL Server
var options = new SqlServerBulkInsertFromQueryOptions
{
    TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};

// PostgreSQL
var options = new NpgsqlBulkInsertFromQueryOptions
{
    TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers", "archive")
};

// MySQL
var options = new MySqlBulkInsertFromQueryOptions
{
    TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};

// SQLite
var options = new SqliteBulkInsertFromQueryOptions
{
    TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("ArchiveCustomers")
};

await ctx.Set<Customer>().BulkInsertAsync(sourceQuery, mapBuilder, options);

The provider is called for the target entity type only. schema == null means that no schema is emitted, so the database uses its default schema. On MySQL, a schema follows the SchemaBehavior rule of Table override. The options TableName and Schema are obsolete, see Table override.

Generated SQL

All four providers generate the same structure (only identifier quoting differs):

-- SQL Server
INSERT INTO [Schema].[Table] ([Col1], [Col2])
SELECT s.[SrcCol1], s.[SrcCol2]
FROM (
  <source_query>
) AS s;

-- PostgreSQL / SQLite
INSERT INTO "Schema"."Table" ("Col1", "Col2")
SELECT s."SrcCol1", s."SrcCol2"
FROM (
  <source_query>
) AS s;

-- MySQL (no schema)
INSERT INTO `Table` (`Col1`, `Col2`)
SELECT s.`SrcCol1`, s.`SrcCol2`
FROM (
  <source_query>
) AS s;

Limitations

Default values

Depending 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 insert would contradict the whole idea of this feature.

Possible solutions:

  • Provide all values explicitly (i.e. don't depend on the database or EF to set default values)
  • Don't insert entities as a whole, skip the properties with default values

MS SQL Server

It is not possible to trigger the default value constraint of the SQL Server if the column is NOT NULL

  • If the corresponding .NET-Property is a reference type (like a string) then SqlBulkCopy will throw a InvalidOperationException with a message Column 'MyStringColumn' does not allow DBNull.Value.
  • If the corresponding .NET-Property is a not-nullable struct (like an int) then the value is written to the database as-is, i.e. if the .NET-value is 0 then 0 is written into database. The same is true for a Guid, i.e. an empty Guid stays 00000000-0000-0000-0000-000000000000.

If the column allows NULL then .NET-Value null will trigger the default value constraint, i.e. we get the expected result.

SQLite

With SQLite the default value constraint doesn't trigger when trying to send null / NULL / DBNull.Value to both NULL and NOT NULL columns. The only way to trigger the constraint is not to insert the corresponding property alltogether.

Shadow Properties

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.

Clone this wiki locally