I'm using EFCore to steaming data to backend db, I call SaveChanges
for every a certain number of new objects added to the dataset, I noticed from the EFCore debug log that it will close the connection and open a new one each time I call SaveChanges
:
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Opening connection to database ...
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Beginning transaction with isolation level 'Unspecified'.
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Committing transaction
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Closing connection to database...
.... the logs repeats forever
So is there anyway to just use one connection for the entire lifecycle of a DbContext
?
There's no real need for you to change how this works, or even worry about it at all. By default, SQL Server connections are just put back into a connection pool so in reality it doesn't get closed. Opening a new one will just grab the next available on in the pool.
You can control the pool if you really want by setting values in the connection string, while I would advise against that unless you really know what you are doing, these are the main properties that are used (from MSDN):