WriteToServer: Connection property has not been initialized. sqlbulkcopy error

c# sqlbulkcopy

Question

running sqlbulkcopy in c# and I get an error: WriteToServer: Connection property has not been initialized.

it happens at the WriteToServer command. The connection is open.

using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
  foreach (DataTable dt in ds.Tables)
  {

    s.DestinationTableName = "tmp_" + dt.TableName;
    s.NotifyAfter = 5000;
    s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
    s.WriteToServer(dt);
    s.Close();
  }
}

Correct Code:

using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
  foreach (DataTable dt in ds.Tables)
  {
    s.DestinationTableName = "tmp_" + dt.TableName;
    s.NotifyAfter = 5000;
    s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
    s.WriteToServer(dt);
  }
  s.Close();
}

Accepted Answer

At a glance I would guess that the first pass through the foreach loop is executing correctly, then s.Close(); is cleaning up the SqlBulkCopy instance and clearing its Connection property, thus creating the exception on the second pass.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why