[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 499
  • Last Modified:

How to handle null db fields in DAL

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?
2 Solutions
One thing that they might do is

use Convert.ToInt32 instead of(int) for casting. coz Convert is capable of handling nulls..
hope it will work,

To check nulls in C# you can use IsNullOrEmpty() of String class.
---> will return true, if the result is Null or empty, in other case, you can convert it into your target format by Convert.To.....() or your own customized code..

in your case,
int topicId = string.IsNullOrEmpty(reader["TopicID"].ToString()) ? 0 : (int)reader["TopicID"],

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now