I have table defined like this:
CREATE TABLE [staging].[tbPositionAssetIdentifier]
(
[StageID] [int] IDENTITY(1,1) NOT NULL,
[AssetId] [nvarchar](50) NULL,
[SecurityDescription] [nvarchar](max) NULL,
[Sedol] [nvarchar](50) NULL,
[isin] [nvarchar](50) NULL,
[secTicker] [nvarchar](50) NULL,
[secType] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED ([StageID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
And I have class defined for it:
public class AssetData
{
[JsonPropertyName("assetId")]
public string? AssetID { get; set; }
[JsonPropertyName("secDesc1")]
public string? SecurityDescription { get; set; }
[JsonPropertyName("sedol")]
public string? Sedol { get; set; }
[JsonPropertyName("secTicker")]
public string? secTicker { get; set; }
[JsonPropertyName("isin")]
public string? isin { get; set; }
[JsonPropertyName("secType")]
public string? secType { get; set; }
}
I am trying to save a list of AssetData into the database table tbPositionAssetIdentifier using SqlBulkCopy as shown below, but it is failing with an exception
The given ColumnMapping does not match up with any column in the source or destination
Code:
public static async Task SaveToDBAsync(
List records,
string connectionString,
string tableName)
{
if (records == null || records.Count == 0)
return;
var entityType = typeof(T);
var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead)
.ToList();
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
using var bulkCopy = new SqlBulkCopy(connection);
bulkCopy.DestinationTableName = tableName;
var dataTable = new DataTable();
foreach (var property in properties)
{
bulkCopy.ColumnMappings.Add(property.Name, property.Name);
dataTable.Columns.Add(property.Name, property.PropertyType);
}
foreach (var record in records)
{
var row = dataTable.NewRow();
foreach (var property in properties)
{
row[property.Name] = property.GetValue(record) ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
await bulkCopy.WriteToServerAsync(dataTable);
}
Is this Exception coming because I have an Identity incrementing PK column in Table where as in class (or model) I don't have that column, why is the Column mismatch is happening?
Could somebody please help me why is it failing and what is the solution for it? Any help or any advice would be appreciated. Thanks in advance