通过 sqlbulk 插入 SQL

inserting into SQL via sqlbulk

你好,我有这样的狙击代码:

 public static void Put_CSVtoSQL_Adhesion()
    {
        bool IsFirst = true;      
        DataTable dt = new DataTable();
        string line = null;
        int i = 0;

        try
        {
            string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);

            using (StreamReader sr = File.OpenText(fileName))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] data = line.Split(';');
                    if (data.Length > 0)
                    {
                        if (i == 0)
                        {
                            foreach (var item in data)
                            {
                                dt.Columns.Add(new DataColumn());
                            }
                            i++;
                        }
                        DataRow row = dt.NewRow();
                        row.ItemArray = data;

                        // Pour enlever la tete 
                        if (!IsFirst) dt.Rows.Add(row);
                        IsFirst = false;
                    }
                }
            }

            using (var connectionWrapper = new Connexion())
            {
                var connectedConnection = connectionWrapper.GetConnected();
                using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
                {
                    int CountColl = dt.Columns.Count;

                    copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);


                    copy.DestinationTableName = "cotisation";
                    copy.WriteToServer(dt);
                }
            }
        }
        catch (Exception excThrown)
        {
            throw new Exception(excThrown.Message);
        }
    }

此代码运行良好,但现在我有 60 多列,我应该手动输入 1 到 60 列还是有其他方法?

 copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);

...直到第 60 列?

该列完全相同我只是移动了 1 列,因为第一列是作为 ID 自动递增的列

写一个循环?

for (int i = 0; i < dt.Columns.Count - 1; i++)
{
    copy.ColumnMappings.Add(i, i + 1);
}