Bulk insert using code first migrations for azure

279 views Asked by At

We have a lot of data that needs to be loaded into a number of tables. As far as I can see we have two options:

  1. Include the data as part of the Configuration class seed method Problems 1.a. this would be slow and involve writing a lot of C# code)

  2. Use bulk insert with code first migrations - a lot quicker and probably a better solution. Problems 2.a. It may prove tricky working with other data that gets loaded into the same tables as part of the seed. 2.b. It requires SQL Identity Insert to be switched on.

What solution is best and if it is 2 how do I go about bulk insert with code first migrations and how can I address the problems?

1

There are 1 answers

0
Rowan Miller On

Bypassing EF and using ADO.NET/SQL is definitely a good approach for bulk data upload. The best approach depends on whether you want the data to be inserted as part of migration or just logic that runs on app start.

  • If you want it to be inserted as part of a migration (which may be nice since then you don't have to worry about defensive checks if the data exists etc.) then you can use the Sql(string) method to execute sql that uses whatever format and sql features you want (including switching IDENTITY_INSERT on/off). In EF6.1 there is also an overload that allows you to easily run a .sql file rather than having everything in code as a string.
  • If you want to do it on app start, then just create an instance of your context and then access Database.Connection to get the raw SqlConnection and use ADO.NET directly to insert the data.