Savage
Savage

Reputation: 2349

Most common practice for managing ObjectContext in EF

I'm really confused about the standard way to create and dispose of your context for my MVC3 app with multiple layers. I started with EF4 and upgraded to EF5, and the default MSDN tutorials always seem to indicate working within using blocks, which seems particularly lousy - it seems to me that I have to pass the context object up and down the method chain.

I've done a fair bit of reading about context per request, repository patterns, unit of work patterns, etc, and it seems everyone is reinventing the wheel.

Are developers really sitting on a plethora of different EF implementations, or is there a common approach that I missed in a master tutorial?

Upvotes: 0

Views: 108

Answers (2)

MaxSC
MaxSC

Reputation: 4758

There might have a few different ways to implement UoW and Repository pattern but one thing everyone agree with is that it's pretty useful because they create an abstraction level over the Context created by Entity Framework.

There are several reasons not to use directly the EF DBContext, two of them are preventing misuse and abstract complex features that should not be exposed to all the developers.

Now, concerning the implementation, I did not feel like reinventing the wheel when I came up using UoW and Repositories that way. Please have a look and tell me what you think! It's pretty straightforward.

Hope that helps!

Upvotes: 1

Justin
Justin

Reputation: 3397

What you need to really remember is the underlying context is still a DbConnection. It is recommend to wrap it in a using statement so you don't forget to dispose of it when you are done.

Other than that, it really depends on what you are doing. Sometimes wrapping in a using statement is fine. Other times you may need to keep a instance of it and keep using it, again, just remember to dispose of it when you are done.

I think the reposition pattern is fairly popular with abstracting the context so you can just call methods on the repository and then return the results from the context and keep it alive.

Upvotes: 0

Related Questions