Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BulkInsertAsync with SqlBulkCopyOptions.KeepIdentity inserts NULLs instead of provided IDs #1693

Open
Bigfellahull opened this issue Feb 27, 2025 · 0 comments

Comments

@Bigfellahull
Copy link

When performing a bulk insert with SqlBulkCopyOptions.KeepIdentity, the expected behaviour is that IDs provided in the entity list should be inserted as-is. However, due to how default values are handled in InnerGetDataTable, NULLs are inserted instead, leading SQL Server to generate new IDs.

Steps to Reproduce:

  • Create an entity with a GUID primary key.
  • Populate a list of entities with pre-generated IDs.
  • Call BulkInsertAsync with KeepIdentity:
var bulkConfig = new BulkConfig
{
    SqlBulkCopyOptions = SqlBulkCopyOptions.KeepIdentity
};
await dbContext.BulkInsertAsync(documents, bulkConfig);
  • Observe that SQL Server generates new IDs instead of using the provided ones.

Expected Behaviour:
The provided IDs should be inserted into the identity column.

Actual Behaviour:
NULLs are inserted instead, causing SQL Server to generate new IDs.

Root Cause:
The logic in InnerGetDataTable excludes columns with default values during insert

var hasDefaultValueOnInsert = tableInfo.BulkConfig.OperationType == OperationType.Insert
    && !tableInfo.BulkConfig.SetOutputIdentity
    && tableInfo.DefaultValueProperties.Contains(property.Name);

Proposed Fix:
Modify hasDefaultValueOnInsert to check for KeepIdentity before excluding default value columns:

var hasDefaultValueOnInsert = tableInfo.BulkConfig is { OperationType: OperationType.Insert, SetOutputIdentity: false }
    && tableInfo.DefaultValueProperties.Contains(property.Name)
    && !tableInfo.BulkConfig.SqlBulkCopyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);

This ensures the ID column is included when KeepIdentity is specified.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant