I am using the repository pattern where I have one repository class per database table. I was wondering how you guys approach queries that only need to return a specific number of columns
For example say I have the following
Item Table (fictional table)
ItemId
Name
PurchaseDate
Description
Price
In my code I create an object with the fields above called Item.cs (currently not using an orm).
If I have multiple scenarios where I need to return
- ItemId
- A combination of PurchaseDate and Name
- ItemId and price
Which would be the best approach?
- Get all fields from the items table and return an Item object (1 repo query)
- Create three queries in Repo and return an Item object for each one
- Create three queries in Repo and return only what is needed?
Now imagine this scenario with a table with over 10 fields.
Personally, I like option one, but I’m not sure if there is a better way to go about this.
I personally use a generic type repository and and have my read
AsQueryable()Here’s the interface.
and here’s the implementation.
Now if you need to query the repository, you want to do something like this.
forgive me, the below code is untested and I’m actually more of a VB guy 🙁
hopefully you get the point
For my purposes, I’m using LINQ on this particular project, but this can be adapted to whatever data layer you like… that’s the beauty of a repository layer.
From here I “personally” also have a Service Layer that deals with the nuances of data connection… things like
GetPersonByIDorGetPeopleSince(DateTime marker). This is where I strip out the information that I don’t need (IE: passwords) and store the remaining information in either a ViewModel or some other POCO.