EF.DbContextFactory icon indicating copy to clipboard operation
EF.DbContextFactory copied to clipboard

I am having doubts while learning DbContextFactory

Open shouhujishu opened this issue 3 years ago • 1 comments

Hello. I am having doubts when using DbContextFactory. Is there any difference between CreateDbContext() and new DbContext()? Is there any difference between using DbContextFactory and using(=new DbContext())? Thank you, can you tell me?

shouhujishu avatar Jan 13 '21 10:01 shouhujishu

@shouhujishu I don't know if you are still learning EF Core, but after spending a good amount of time, it seems there is really no best solution. If you create a new instance each time, sure, you might escape concurrency problems, but you lose other properties of EF Core, like Caching. And then if you want to span a DB transaction across multiple services, how do you do that? I am not an expert myself, but I would say you CAN'T. You'd have to pass around your original context and chose a point where you'd want to commit your transaction, or roll it back if you have any errors. Each approach has pros and cons, so you'd have to make the choice yourself. I don't think there's any bad approach (putting aside using the same DbContext within multiple threads).

andreyeurope avatar Aug 10 '21 08:08 andreyeurope