Skip to content

SqlBulkCopy fails with InvalidOperationException when target table has computed columns #20

@priyankatiwari08

Description

@priyankatiwari08

Describe the bug

When using SqlBulkCopy to insert rows into a table that has a computed column, the operation fails with InvalidOperationException: The given ColumnMapping does not match up with any column in the source or destination even though all non-computed columns are correctly mapped.

To reproduce

// Target table:
// CREATE TABLE Orders (
//   Id INT IDENTITY PRIMARY KEY,
//   Quantity INT,
//   UnitPrice DECIMAL(10,2),
//   TotalPrice AS (Quantity * UnitPrice) PERSISTED
// )

using var bulkCopy = new SqlBulkCopy(connection);
bulkCopy.DestinationTableName = "Orders";
bulkCopy.ColumnMappings.Add("Quantity", "Quantity");
bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice");

var dt = new DataTable();
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("UnitPrice", typeof(decimal));
dt.Rows.Add(5, 19.99m);

await bulkCopy.WriteToServerAsync(dt); // throws InvalidOperationException

Expected behavior

SqlBulkCopy should skip computed columns automatically when explicit column mappings are provided for the non-computed columns only.

Actual behavior

System.InvalidOperationException: The given ColumnMapping does not match up with any column in the source or destination.
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServerAsync(...)

Further technical details

Microsoft.Data.SqlClient version: 6.0.0
Target framework: .NET 8.0
SQL Server version: SQL Server 2022 (16.0.4135)
Operating system: Windows Server 2022

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions