I'm creating a simple blog in asp.net 4 using sql server 2008. I'm using books as a reference which include samples of business logic layer (BLL) and data access layer (DAL).
The table to store my posts has the expected items - title, body, etc. Some of the fields can be null. In my data access class, which maps the db fields to a "post" data entity, when I read a null db column into an enitity property, I get an invalid casting error unless I explicity handle nulls.
So, I'm now checking for null before setting the property if the field may be null, like this:
return new PostEntity(
reader["TopicID"] == DBNull.Value ? 0 : (int)reader["TopicID"],
reader["CreatedDateTime"] == DBNull.Value ? new DateTime() : (DateTime)reader["CreatedDateTime"],
reader["Intro"] == DBNull.Value ? "" : (string)reader["Intro"],
........ //rest of code here
This code works.
This makes sense, but the books I'm using don't do this - even when using db fields which can be null. They just read the values into the entity. Now, I've not actually run their code, but assuming their code does work - how? Is it not necessary to do what I'm doing to handle null db values? What's the "right" way to do this? Is their a good example online of a solution?