Shawn Mclean
Shawn Mclean

Reputation: 57479

Database context in a singleton for repository pattern

The way I currently design systems is that each repository has its own database context. I dependency inject the connection string for each repository.

But lets say 1 page calls 2 or more (n) repositories, this means there are n seperate calls going to the database. Using ORMs like entity framework with lazy loading, is it possible that my queries can be merged at the end of the repository level into 1 call if I share 1 database context?

How do I accomplish this? Could someone give me a basic outline/structure of how I'd use 1 single context for all repositories? Thanks.

Upvotes: 1

Views: 1440

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364369

With entity framework your queries will never be merged to single call. That is limitation of current EF implementation. But having single context per one http reqeuest (best practice) is way to go. Instead of injecting query string inject whole context.

Upvotes: 1

Related Questions