BluePalmTree
BluePalmTree

Reputation: 333

How to manage DbContext in a WPF Applicatoin

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?

Upvotes: 0

Views: 176

Answers (1)

DonBoitnott
DonBoitnott

Reputation: 11025

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.

Upvotes: 1

Related Questions