6

I have a db table with several DateTime fields with null values. These are mapped to nullable DateTimes in my class.

If I try to perform an update with Dapper, within my data layer:

 using (IDbConnection cnn = new SqlConnection(DB.getConString()))
 {
    cnn.Open();
    return cnn.Execute((this.OptionID == 0 ? _insertSQL : _updateSQL), this);              
 }

I get a SqlDateTimeOverflow exception (because the DateTime field is '01/01/0001 00:00:00' rather than null.

Is the only way around this to specify each parameter individually and switch the value to null like this:

 using (IDbConnection cnn = new SqlConnection(DB.getConString()))
 {
    cnn.Open();
    return cnn.Execute("UPDATE MyTable SET MyDateField = @MyDateField", new {MyDateField = (MyDateField.HasValue? MyDateField : Null), etc etc... );

I have about 50 fields in the table so this would be quite a bit of code, plus there is an INSERT method to update similarly too. Is there an easier syntax I am missing?

0

1 Answer 1

7

The issue here is that 01/01/0001 00:00:00 is not a "null value"; if you had used DateTime? I suspect it would have worked fine. However, I also have to recognize that DateTime.MinValue has often (mainly due to .NET 1.1 lacking nullable structs) been used to represent a null value. My preferred suggestion here would be to simply use DateTime?. The min-value map is a bit complicated as we might also consider whether that should be automatically mapped instead to the sql min-value (January 1, 1753).

Re the update statement - maybe add an extension method to map between min-value and null?

public static DateTime? NullIfZero(this DateTime when) {
    return when == DateTime.MinValue ? (DateTime?)null : when;
}

and use:

new { MyDateField = MyDateField.NullIfZero() }

but again, if MyDateField was DateTime?, you could just use:

new { MyDateField }
5
  • Yes, the property is already DateTime? but it doesn't end up as null. For example: public DateTime? ReleaseDate { get; set; }.
    – Simon
    May 9, 2013 at 12:53
  • @Simon yes, but what is the value in it? A DateTime? that has the value 01/01/0001 00:00:00 is not null; if you want it to be null - store it as a null. May 9, 2013 at 13:00
  • The value is null in the database if that's what you mean?
    – Simon
    May 9, 2013 at 13:03
  • The 01/01/0001 was coming from a rogue control on a page, I've fixed this and am now passing in a genuine null, I still get the same exception though. I'll accept this answer and create another question.
    – Simon
    May 9, 2013 at 14:12
  • Problem solved, as expected it was entirely my fault, Dapper works fine. I had declared a datetime field as a string by mistake. Great service as usual Marc.
    – Simon
    May 9, 2013 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.