Home > OS >  How to manage DbContext in a WPF Applicatoin
How to manage DbContext in a WPF Applicatoin

Time:03-22

I overtook a WPF project where entity framework is used. The person before me used a single global DbContext. After some reading it became clear that this is a bad practice because of several reasons. Now my job is to refactor the project to use a DbContextFactory and create new DbContext per unit-of-work. One method i.e. SaveSales calls another method IncreaseReceiptNumber. Inside IncreaseReceiptNumber an entry is added to a table and SaveChanges is called. Now inside SaveSales i create a DbContext with using (var clientDB = dbContextFactory.Create() {}. My question is, in a case like this should I pass the DbContext from SaveSales to IncreaseReceiptNumber or should IncreaseReceiptNumber create it's own DbContext? Or in a more general sense, should every method create a new DbContext or can a DbContext passed on via parameter if it belongs to the unit-of-work?

CodePudding user response:

You want to encapsulate every specific transaction into a using directive:

using DBContext dbContext = dbContextFactory.Create()
{
    // use the dbContext in here
    // once it has no need to exist anymore, it gets disposed
}

So yes, every method should have their own using directive in this case.

CodePudding user response:

IMO, there is no single answer to this question. You must decide for each case whether or not the overhead of multiple connections is warranted (overhead is small with pooling, but exists), if the sharing of a single DbContext provides extra benefits (entities already attached), and if sharing makes things more difficult (you're calling the method in a loop, and risk "connection already open" errors) . These factors have to be weighed on a case-by-case basis. For what it's worth, I have done all of these things...use the right tool for the job, as they say.

  • Related