I was trying to Add() about 18000 objects to my DBContext. It took around 5 minutes. Saving this data with SaveChanges() took even longer. I switched to creating a normal List and adding my objects to it, whereafter i used SqlBulkCopy to persist the data. This took about 5 seconds.
What does the Add method do, that makes it take so long?
The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder . Learn how to configure a DbContext class at here.
Use the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method.
It is a bridge between your domain or entity classes and the database. DbContext is the primary class that is responsible for interacting with the database. It is responsible for the following activities: Querying: Converts LINQ-to-Entities queries to SQL query and sends them to the database.
Implicitly sharing DbContext instances via dependency injection. The AddDbContext extension method registers DbContext types with a scoped lifetime by default.
So what happens is that on each add call DetectChanges is executed on the context. This enumerates the entire object graph, so the more items you track the longer each individual add will take. Theres a bunch of tuning you can do around this as well to stuff go fast (i get approx 1k/s inserts on my home vm).
Effectively without tuning EF add performance is O(n^2)
I go into this in quite a bit of detail in the following article:
EntityFramework Performance and AutoDetectChanges
For more deets about how fast EF can perform when tuned take a look here:
Entity Framework Comparative Performance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With