User283571144 posted
Hi brucey,
As far as I know, we couldn't directly convert the dbcontext to sql connection when we want to use SqlBulkCopy with Entity Framework.
We could only get the connection string from the DbContext's Database.Connection.ConnectionString property and use it works with the SqlBulkCopy.
More details, you could refer to below codes:
using (ApplicationDbContext dbcontext = new ApplicationDbContext())
{
SqlConnection sqlCon = new SqlConnection(dbcontext.Database.Connection.ConnectionString);
sqlCon.Open();
using (SqlBulkCopy s = new SqlBulkCopy(sqlCon))
{
//set the table name
s.DestinationTableName = "AspNetUsers";
foreach (var column in d.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(d);
}
sqlCon.Close();
}
But, this also using ado.net concept not EF, if you want to directly using EF to bulk copy, you could try to use below library:
https://github.com/MikaelEliasson/EntityFramework.Utilities
It works well for simple bulk inserts and updates.
You should also look at the following post if you want to find out about other options to achieve bulk insert:
https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
Best Regards,
Brando