How to get single object when using repository pattern?

I'm using a homebrewed repository pattern (!) together with PetaPoco in my latest project. And when coding some data retrieval routines my brain suddenly made a jump.

Currently i have Repo.GetMyObjects that returns an IList<MyObject> from the db, and a Repo.GetMyObject that returns a MyObject.

Is this the correct way to go ahead? Or should I have my Repo.GetMyObjects return an IEnumerable<MyObject> and then use Repo.GetMyObjects().SingleOrDefault( q => q.ID == MyWantedObjectID) in my controller to get a single object?

Upvotes: 0

Views: 1032

Answers (3)

Andrew Barber
Andrew Barber

Reputation: 40150

To go even further than Ankur's answer: the way you are doing is actually more correct, because having to add SingleOrDefault() calls would seem to be something the repository should be doing for you.

Upvotes: 1

Frederik Gheysels
Frederik Gheysels

Reputation: 56964

It would be stupid to retrieve a whole collection of MyObject instances, if you only need one. Consider the performance-cost that this gives you, if you have thousands of instances in your database.

So, you'll need a GetMyObject method in your repository, which retrieves the only object you're interested in.

Upvotes: 0

Ankur
Ankur

Reputation: 33657

Let your Repo.GetMyObject bet there and make it do what you have described. So that in future if required you can change the implementation and all the callers won't need any change.

Upvotes: 0

Related Questions