I’m struggling to define a class method that populates and returns a collection of instances. The issue I don’t know how to get around is that I have private attributes to populate.
Let’s use the example of a Book class. I don’t want the code to directly set (say) the availability of a book. I want the code to have to use a CheckOut method on a Book instance. So we have something like:
public class Book { private int ID; private bool pAvailableForCheckout; public string Title { get; set; } public bool AvailableForCheckout { get { return pAvailableForCheckout } } // instance methods public Book(int BookID) { // Load book from DB by ID } public CheckOut() { // perform everything involved with checking a book out } // .. other methods like saving a book, checking out books etc. // class method public static List<Book> FindAll() { // load Dataset of books // foreach record in DB, use the Book(int BookID) constructor and add to List // return list of books } }
So, I can do use this in my code:
foreach(Book curBook in Book.FindAll()) { /* do something with book */ }
The problem with the above implementation is that I have to use N+1 hits to the database to load all the books instead of just 1 query. How do I get around this?
I’m sure this is programming 101, but I needed to ask.
You could create a protected constructor which populates the private properties directly.