Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDateTime overflow error when saving DateTime.MinValue on a POCO entity

I've been having som issues when saving POCO entities with a DateTime property. When the DateTime property has the value of DateTime.MinValue the SaveChanges() fails because of the difference between SqlDateTime.MinValue and DateTime.MinValue.

So, what to do?

1) Should I check for DateTime.MinValue before saving the entity?

2) Should I have my datetime POCO property designed something like this?

    private SqlDateTime _created;
    public virtual DateTime Created
    {
        get
        {
            return _created.Value;
        }
        set 
        {
            _created = value == DateTime.MinValue ? SqlDateTime.MinValue : value;
        }
    }

/PW

like image 948
Peter Wikström Avatar asked Apr 05 '11 10:04

Peter Wikström


2 Answers

If possible, I'd recommend making the database field nullable and set the value to null rather than min value.

Alternatively I would design the property like this:

private SqlDateTime? _created;
public virtual DateTime Created
{
    get
    {
        return (DateTime)(_created ?? SqlDateTime.MinValue);
    }
    set
    {
        if (value == null || value < (DateTime)SqlDateTime.MinValue)
        {
            _created = SqlDateTime.MinValue;
        }
        else 
        {
            _created = (SqlDateTime)value;
        }
    }
}
like image 131
Emil Badh Avatar answered Nov 09 '22 15:11

Emil Badh


The simplest approach I can think of is to initialize DateTime properties to (DateTime)SqlDateTime.MinValue:

public class SomeEntity
{
    public SomeEntity()
    {
        Updated = (DateTime)SqlDateTime.MinValue;
    }

    public DateTime Updated { get; set; }
}
like image 36
dajo Avatar answered Nov 09 '22 14:11

dajo