1

I have for a long time used SqlBulkCopy with Entity Framework. I have just migrated to Entity Framework Core. Before I did something like:

var itemsDT = jobs.ToDataTable<ProfileJob>();

using (var connection = new SqlConnection(_connStr))
{
    connection.Open();

    using (var bulkCopy = new SqlBulkCopy(connection))
    {
        bulkCopy.BatchSize = 1000;
        bulkCopy.DestinationTableName = "dbo.JobRemoveUniquePermissionsFailed";
        bulkCopy.WriteToServer(itemsDT);
    }
}

The ToDataTable was a large extension class build on the old Entity Framework. I haven't found any samples on something similar with core.

Does anyone have a small sample how to use SqlBulkCopy with EF Core?

1 Answer 1

6

I have a small code sample that covers this here. There's just a single code file you add to your project, giving you .AsDataReader() and .ToDataTable() extension methods. EG:

    static int SendOrders(int totalToSend)
    {
      using (SqlConnection con = new SqlConnection(connectionString))
      {
        con.Open();
        using (SqlTransaction tran = con.BeginTransaction())
        {
          var newOrders =
                  from i in Enumerable.Range(0, totalToSend)
                  select new Order
                  {
                    customer_name = "Customer " + i % 100,
                    quantity = i % 9,
                    order_id = i,
                    order_entry_date = DateTime.Now
                  };
      SqlBulkCopy bc = new SqlBulkCopy(con,
        SqlBulkCopyOptions.CheckConstraints |
        SqlBulkCopyOptions.FireTriggers |
        SqlBulkCopyOptions.KeepNulls, tran);

      bc.BatchSize = 1000;
      bc.DestinationTableName = "order_queue";
      bc.WriteToServer(newOrders.AsDataReader()); 

      tran.Commit();
    }
    con.Close();

  }

  return totalToSend;

}
Sign up to request clarification or add additional context in comments.

2 Comments

Tested and worked! Thanks alot - highly appreciated.
Is it possible to get identity column somehow with this code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.