Bye
Bye

Reputation: 2806

Re: UnitOfWork - can the context be decoupled?

I just finished watching Julie Lerman's video on Enterprise EF. I especially like the concept of custom data context as it would give me more granular control over the respective UI's.

Julie has CRUD methods in all her respositories and that is just way too much coding for my likes. I plan to create a Generic Repository that other repositories derive from. I did not like her UOW.

I plan on using this approach to UOW as it relates to the repositories:

https://codereview.stackexchange.com/questions/14226/generic-repository-and-unit-of-work-code

Relative conditions with custom data context objects:

  1. Let's assume I create:

    i. CustomerLookup class that only has partials properties of the full Customer class.

  2. I also create

    i. a CustomerLookup db context

    ii. an OrdersLookup db context that has the complete Orders class but ignores the associated entity Shipping in the configuration.

If I follow the UOW example in the link above, the UOW uses the FULL DbContext to save changes.

Question:

  1. Is it possible to instantiate the UOW, when in the API controller as example, so that a specific data context can be used:

    i. CustomerLookupContext with UOW.CustomerLookupRepository.Update(customerLookup)?

    ii. OrdersLookupContext with UOW.OrdersLookupRepository.Update(order) ?

If I cannot decouple the context object from UOW:

  1. Will I have a problem updating partial classes like above; or
  2. Does using the whole DbContext affect performance; or,
  3. I have no idea what I'm talking about & just use UOW's full DbContext?

Thanks

Upvotes: 0

Views: 272

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

You should only ever have one dbcontext in an app. There are exceptions, like when you need to access two different databases, but even then I prefer to use SQL Server Synonyms to map them into a single database.

There are very real problems with putting more than one context in an app. You will get lots of compiler errors and have to deal with namespace collisions. It's possible to work around it, but it's a big pain.

There is no benefit from making different contexts for different uses. The whole point of the dbcontext is that you can have full access to the database, make changes in different entities, and then save all changes in one operation.

What is it you think you are gaining? It's not like it loads the whole database into memory.

Upvotes: 1

Related Questions