SQL 当你有 GUID (UniqueIdentifier) 列时在 C# 中批量插入

SQL Bulk Insert in C# when you have GUID (UniqueIdentifier) Column

我需要将数据从一个 table 复制到另一个 table。 我收到一条异常消息:

The given value of type String from the data source cannot be converted to type uniqueidentifier of the specified target column",

因为我有 GUID 数据类型的列。

我的代码...

using (SqlConnection destinationConn = new SqlConnection("Data Source = ''; Initial Catalog = ''; Persist Security Info = True; User ID = ''; Password = ''; MultipleActiveResultSets = true"))
            {
                using (SqlBulkCopy bc = new SqlBulkCopy(destinationConn))
                {
                    bc.DestinationTableName = "Animal";

                    destinationConn.Open();

                    bc.ColumnMappings.Add("guid", "guid"); //UniqueIdentifier
                    bc.ColumnMappings.Add("Name", "Name");
                    bc.WriteToServer(dt);  //DATA TABLE object


                }
            }

我该如何解决这个问题?

我遇到了类似的问题,用下面的代码解决了。

                DataTable dt = new DataTable();
                dt.Columns.Add("IdColumn1", typeof(Guid));
                dt.Columns.Add("IdColumn2", typeof(Guid));
                foreach (var item in MyCollection)
                    dt.Rows.Add(item.obj1, item.obj2);

                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    con.Open();

                    using (var bulkCopy = new SqlBulkCopy(con))
                    {
                        bulkCopy.DestinationTableName = "TableName";
                        bulkCopy.ColumnMappings.Add("IdColumn1", "IdColumn1");
                        bulkCopy.ColumnMappings.Add("IdColumn2", "IdColumn2");
                        bulkCopy.WriteToServer(dt);
                    }
                    dt.Dispose();
                }