Assume I have a declared a datatable and to this datatable I have assigned a result that gets returned from calling a stored procedure, so now, my datatable contains something like the following when accessing a row from it:
string name = dr["firstname"];
int age = (int)dr["age"];
if firstname is changed to first_name and age is removed, the code will obviously break because now the schema is broken, so is there a way to always keep the schema in sync with the code automatically without manually doing it? Is there some sort of meta description file that describes the columns in the database table and updates them accordingly? Is this a case where LINQ can be helpful because of its strongly typed nature?
What about good old fashioned views that select by column name, they always output the columns with the specified names in the specified order. If the table underneath needs to change, the view is modified if necessary but still outputs the same as it did before the underlying table change – just like interfaces for your objects. The application references the views instead of the tables and carries on working as normal. This comes down to standard database application design which should be taught in any (even basic) data architect course – but I rarely see these actually used in business applications. In fact, the project I’m currently working on is the first where I’ve seen this approach taken and it’s refreshing to actually see it used properly.
Use stored procs, if your table changes, modify the stored proc so the output is still the same – used in a similar manner to shield the application from the underlying table thus insulating the application from any table changes. Not sufficient if you’re looking to do dynamic joins, filters and aggregates where a view would be more appropriate.
If you want to do it application side, specify the names of the fields you’re querying right in the query rather than using “select *” and relying on the field names to exist. However, if the field names on the table change, or a column is deleted, you’re still stuck, you’ve gotta modify your query.
If the names of fields will change, but all of the fields will always exist, the content of those fields will remain the same and the fields will remain in the same order, you could reference the fields by index instead of by name.
Use an object relational mapper as others have specified, but I don’t think this necessarily teaches good design rather than hopes the design of the framework is good enough and appropriate for what you’re doing, which may or may not be the case. I’m not really of the opinion this is a good approach though.