-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: Nullable DateTime in .NET 2.0
PostPosted: Tue Nov 15, 2005 11:34 am 
Newbie

Joined: Fri Nov 04, 2005 2:45 pm
Posts: 18
Location: Gainesville, FL
This is, I think, a fairly common problem, and I'm wondering if anyone has come up with a solution.

I need to persist an object to/from a SQL Server DB. This object features a date; the date is optional and so SQL Server allows nulls in that column.

If you've tried to persist dates in NHibernate before you know the problem I'm running in to; when NHibernate populates my objects, the date field is passed a null value, and .NET assigns the minimum allowable date to the field (1/1/0001). If I try to save this object to the database, SQL Server complains because that is way outside the range of allowable SQL Server dates.

I'm working with .NET 2.0, so I tried changing my datetime members to be nullable (using the .NET 2.0 nullable type feature, not the nullable types in NHibernateContrib). This doesn't work; it appears that NHibernate is converting my nullable types to non-nullable DateTime objects?

Using the NHibernateContrib nullable types isn't an option; I'd rather not use NH-specific types in my models.

My problem is two-fold:

1. Is NH in fact doing some typecasting on my nullable types that's keeping their null values from being persisted to the DB, and
2. Is there any way around this?

Thanks for any help or ideas.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Nov 15, 2005 1:45 pm 
Senior
Senior

Joined: Thu Jun 02, 2005 5:03 pm
Posts: 135
Location: Paris
Do you not want to use the NHibernateContrib types because you don't want the consumers of your classes to see them?

If not then you can create your domain objects using field access where the private field is the nullable date-time type and then create a public property which uses .NET standard datetimes and returns the appropriate value. In my case I'm using access="field.camelcase":

Code:
public class DomainObject
{
    private int id;
    private NullableDateTime theDate;

    public int Id
    {
         get { return id; }
    }

    public DateTime TheDate
    {
         get
         {
              return theDate.HasValue ? theDate.Value : DateTime.MinValue;
         }

         set
         {
              theDate = value;
         }

     }
}


Don't know if this is of any use to you, but it works for me!

Cheers,

Symon.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Nov 16, 2005 6:01 am 
Newbie

Joined: Mon Nov 14, 2005 6:29 am
Posts: 2
Actually it's quite easy to just create your NullableDateTimeType ...

Code:
public class NullableDateTimeType : NullableTypesType
    {
        private static DateTime? NULLVALUE = null;

        public NullableDateTimeType()
            : base(new DateTimeSqlType())
        {
        }

        public override object NullValue
        {
            get { return NULLVALUE; }
        }

        public override Type ReturnedClass
        {
            get { return typeof(DateTime?); }
        }

        public override object Get(IDataReader rs, int index)
        {
            return new DateTime?(Convert.ToDateTime(rs[index]));
        }

        public override void Set(IDbCommand cmd, object value, int index)
        {
            IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
            DateTime? nullableValue = (DateTime?)value;

            if (nullableValue.HasValue)
            {
                parameter.Value = nullableValue.Value;
            }
            else
            {
                parameter.Value = DBNull.Value;
            }
        }

        public override object FromStringValue(string s)
        {
            if ((s == null) || (s.Trim().Length == 0))
            {
                return new DateTime?();;
            }
            else
            {
                try
                {
                    return new DateTime?(DateTime.Parse(s));
                }
                catch (System.Exception ex)
                {
                    throw new FormatException("Error parsing '" + s + "' to NullableDateTime.", ex);
                }
            }
        }
    }

in your entity class you do something like that ..

Code:
public class Order {
     private DateTime? _orderDate;
...
    public DateTime? OrderDate
    {
        get { return _orderDate; }
        set { this._orderDate = value; }
    }
...
}



and in your mapping file

Code:
<class name="NorthwindDomain.Order, NorthwindDomain" table="Orders">
...
    <property name="OrderDate" type="NHibernateExtensions.NullableDateTimeType, NHibernateExtensions"/>
...


in this way your model is pure .NET2.0


Top
 Profile  
 
 Post subject:
PostPosted: Wed Nov 16, 2005 10:53 am 
Newbie

Joined: Fri Nov 04, 2005 2:45 pm
Posts: 18
Location: Gainesville, FL
Quote:
Actually it's quite easy to just create your NullableDateTimeType ...


... which is exactly the solution that I eventually came to. ;)

Thanks for the help.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Dec 10, 2005 2:18 am 
Newbie

Joined: Wed Aug 31, 2005 9:29 pm
Posts: 14
nidgir, I tried your solution and got the following error:

The type Nullables.NullableDateTime can not be assigned to a property of type System.Nullable`1[System.DateTime] setter of Contact.BirthDate.

Any ideas?


Top
 Profile  
 
 Post subject: NHibernate and .NET 2.0 Nullable Types
PostPosted: Sat Dec 10, 2005 6:28 am 
Newbie

Joined: Mon Nov 14, 2005 6:29 am
Posts: 2
why don't you just download a complete implementation of nullables for .net2.0:
http://dotavery.com/blog/archive/2005/09/30/5202.aspx[/url]


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.