locked
Assigning nullable datetime value to BusinessObject property RRS feed

  • Question

  • User197122282 posted

    I am populating my BusinessObject from sql server database. One of the properties of the BusinessObject is DateTime shown below:

    ...

    private DateTime dateJoined;
    public DateTime DateJoined
    {
         get { return dateJoined; }
         set { dateJoined = value; }
    }

    I assign a value to the property using the following synxtax:

    myObject.DateJoined = myDataTable.Rows [0]["DateJoined"]

    The problem is that the database field can be null. When I read it from the database and assign it to the property, an exception is thrown "Object cannot be cast from DBNull to other types". How can I read a null value from the database and assign it to the property.

    Sunday, September 8, 2013 5:54 AM

All replies

  • User1564875471 posted

    DBNull.Value represents the database null value, so before setting the property, you need to check for null as below:

    if myDataTable.Rows[0]["DateJoined"] != DBNull.Value
      myObject.DateJoined = myDataTable.Rows[0]["DateJoined"]
    else
     // you can skip the property set or set it to DateTime.MinValue



    Sunday, September 8, 2013 6:42 AM
  • User-1360095595 posted

    Make the property nullable.

    Sunday, September 8, 2013 6:45 AM
  • User1564875471 posted

    Make the property nullable.

    nullable(C# null ) doesn't equal DbNull.Value, so we still need that check.

    Sunday, September 8, 2013 6:57 AM