Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What goes on under the hood of the EF DBContext Add method?

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?

like image 929
Kenci Avatar asked Dec 07 '12 14:12

Kenci


People also ask

Which method is used to add a DbContext to an application?

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.

How do you add a method in Entity Framework?

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.

How does DbContext work in Entity Framework?

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.

Which method allows us to register the DbContext as a dependency?

Implicitly sharing DbContext instances via dependency injection. The AddDbContext extension method registers DbContext types with a scoped lifetime by default.


1 Answers

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

like image 55
Not loved Avatar answered Oct 12 '22 23:10

Not loved