I have a “location” class. This class basically holds addresses, hence the term “location”. I have a datatable that returns multiple records which I want to be “locations”.
Right now, I have a “load” method in the “location” class, that gets a single “location” by ID. But what do I do when I want to have a collection of “location” objects from multiple datatable rows? Each row would be a “location”.
I don’t want to go to the database for each record, for obvious reasons. Do I simply create a new instance of a location class, assigning values to the properties, while looping through the rows in the datatable bypassing the “load” method? It seems logical to me, but I am not sure if this is the correct/most efficient method.
You’re on the right track, getting all the locations you need with one trip to the database would be best in terms of performance.
To make your code cleaner/shorter, make a constructor of your
Locationclass that takes aDataRow, which will then set your properties accordingly. By doing this, you’ll centralize your mapping from columns to properties in one place in your code base, which will be easy to maintain.Then, it’s totally acceptable to loop through the rows in your data table and call your constructor.
You could also use an object to relational mapper, like Entity Framework to do your database interaction.