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