Getting data from a database table to an object in code has always seemed like mundane code. There are two ways I have found to do it:
- have a code generator that reads a database table and creates the
class and controller to map the datafields to the class fields or
- use reflection to take the database field and find it on the class.
The problems noted with the above 2 methods are as noted below
- Method 1 seems to me like I'm missing something because I have to create a controller for every table.
- Method 2 seems to be too labor intensive once you get into heavy data
access code.
Is there a third route that I should try to get data from a database onto my objects?
I think the answer to this depends on the available technologies for the language you are going to use.
I for one am very successful with the use of an ORM (NHibernate) so naturally I may recommend option one.
There are other options that you may wish to take though:
- If you are using .NET, you may opt to use attributes for your class properties to serve either as a mapping within a class, or as data that can be reflected
- If you are using .NET, Fluent NHibernate will make it quite easy to make type-safe mappings within your code.
- You can use generics so that you will not need to make a controller for every table, although I admit that it will be likely that you will do the latter anyway. However the generics can contain most of the general CRUD methods that is common to all tables, and you will only need to code specific quirks.