简体   繁体   中英

Entity Framework Core and SQLBulkCopy

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?

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM