Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Entity Framework with ASP.NET MVC Entity Framework and ASP.NET MVC Handling Reads

Why don't we call directly to the repository Get.. functions?

Instead of creating an instance of the context in the controller and paste the queries inside the controller, why don't we call directly the get methods located in the repository class from the controller? Is it because there the context is closed and then it will give an object disposition exception? Thanks

I was wondering this same thing. This causes duplication of code. Why even have a repository if we are just going to access the tables directly in the controller? We resolved this at my work by requiring an instance of Context in the constructor of the repository, and using that instance for all the methods in the repository. We got the same result, syncing the context's lifetime with the controller's, but without the duplication of code.

James Churchill
James Churchill
Treehouse Teacher

Jared,

You're absolutely correct! As the course progresses, the repository pattern is reintroduced but in a way that makes sense for ASP.NET MVC applications.

Thanks ~James

1 Answer

James Churchill
STAFF
James Churchill
Treehouse Teacher

Albert,

Calling the methods on the existing Repository class shouldn't throw an exception (you could test this and see if that's the case or not). The reason that we're not using the existing Repository class is that each of its methods instantiates its own instance of the Context class, which is less than ideal for an MVC application.

For a discussion on this issue, see this video: https://teamtreehouse.com/library/preparing-our-plan

Thanks ~James