Dispose and create new DbContext

665 views Asked by At

I'm working on a service, where every time it runs, it has to insert thousands of database records (it reads some documents, extracts parameters and then stores those parameters into the database). When it comes to only a few hundreds, there's no big problem, but as more records are being inserted, it gets slower. As far as I know, the main reason behind this is that my DbContext is keeping track of my objects to find any possible modification, and submit an update on a "SaveChanges()" call, and because of that, after a having a certain number of objects, it'll start to degrade its speed, because it'll need to keep track of more and more objects. I know that after certain point, I can get rid of my DbContext to start again from scratch, since I'll no longer need to keep track of those entities, so I tried something like this in my repository class (it'll only do it when it matches my criteria to dispose it):

_dbContext.Dispose();
_dbContext = new DbContext("connectionName");

But if I do it like that, the next time I try to access to the database, I get an exception, saying that my DbContext has been disposed. I also tried just assigning a new instance of DbContext without disposing it first, like:

_dbContext = new DbContext("connectionName");

But by doing it like that, it still keeps all the objects in the _dbContext variable. Since there are a lot of entities, I think that individually dettaching every object from the DbContext will be slower than just creating a new DbContext from scratch, but I don't get why it's not assigning the new DbContext instance (neither after disposing the previous one, nor when just assigning a new instance).

Edit: Just to give you a broader context of what I want to archieve. I actually want the DbContext to keep track of my objects, but after a certain point, I'll not need to keep track of some objects anymore and I'll want it to keep track of a new bunch of objects. Like saying "forget everything you know, now you only care about the new objects that you'll receive". For example, let's say that I'm processing files for a customer, once I finish processing those files, the service will iterate over the next customer, but at this point, I don't really care about keeping track of the objects of the previous customer, and since we might be talking about a few hundreds or thousands of objects (multiple parameters and different entities being inserted into the database), I think that it might be better to just create a new DbContext from scratch, instead of iterating over all my objects to dettach them from my current the DbContext.

0

There are 0 answers