SqlBulkCopy抛出异常:数据源中String类型的给定值无法转换为指定目标列的bigint类型

问题描述 投票:0回答:2

我正在尝试第一次使用SqlBulkCopy。我有一个这样创建的表:

IF NOT EXISTS(SELECT 1 FROM sys.tables 
              WHERE Name = N'DetectionLoggingTime' 
                AND Object_ID = Object_ID(N'dbo.DetectionLoggingTime'))
BEGIN
    PRINT N'Creating [dbo].[DetectionLoggingTime]...';

    CREATE TABLE [dbo].[DetectionLoggingTime]
    (
        [LogId]       INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
        [ScreeningId] BIGINT        NOT NULL,
        [Message]     NVARCHAR(255) NOT NULL,
        [Time]        BIGINT        NULL
    );
END

我试图以这种方式插入值:

public async Task Handle(DetectionLoggingIntegrationEvent @event)
{
    var dt = new DataTable();
    dt.Columns.Add("ScreeningId");
    dt.Columns.Add("Message");
    dt.Columns.Add("Time");

    @event.OperationTimePairs.ForEach(pair => dt.Rows.Add(@event.ScreeningId, pair.Key, pair.Value));

    using (var sqlBulk = new SqlBulkCopy(_configProvider.MyConnectionString))
    {
        sqlBulk.DestinationTableName = "DetectionLoggingTime";
        sqlBulk.WriteToServer(dt);
    }
}

我的感觉是插入试图插入LogId,我希望它是增量的并由SQL Server自动生成。我究竟做错了什么?

c# sql sql-server sqlbulkcopy
2个回答
1
投票

找到解决方案,需要显式列映射:

public async Task Handle(DetectionLoggingIntegrationEvent @event)
{
    var dt = new DataTable();
    dt.Columns.Add("ScreeningId", typeof(long));
    dt.Columns.Add("Message");
    dt.Columns.Add("Time", typeof(long));

    @event.OperationTimePairs.ForEach(pair => dt.Rows.Add(@event.ScreeningId, pair.Key, pair.Value));

    using (var sqlBulk = new SqlBulkCopy(_configProvider.FdbConnectionString))
    {
        var mapping = new SqlBulkCopyColumnMapping("ScreeningId", "ScreeningId");
        sqlBulk.ColumnMappings.Add(mapping);

        mapping = new SqlBulkCopyColumnMapping("Message", "Message");
        sqlBulk.ColumnMappings.Add(mapping);

        mapping = new SqlBulkCopyColumnMapping("Time", "Time");
        sqlBulk.ColumnMappings.Add(mapping);

        sqlBulk.DestinationTableName = "DetectionLoggingTime";
        sqlBulk.WriteToServer(dt);
    }
}

0
投票

这个问题通常是在DataTable中的列类型不明确之前引起的。

例如,设置列类型可能会修复该错误:

var dt = new DataTable();
dt.Columns.Add("ScreeningId", typeof(long));
dt.Columns.Add("Message");
dt.Columns.Add("Time", typeof(long));

有关此问题的更多文档,请访问:https://sqlbulkcopy-tutorial.net/type-a-cannot-be-converted-to-type-b

© www.soinside.com 2019 - 2024. All rights reserved.