7

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

Peter Wikström
  • 261
  • 4
  • 11

2 Answers2

8

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;
        }
    }
}
Emil Badh
  • 4,562
  • 1
  • 17
  • 20
  • Thanks for the response. A follow up question. What about some common way to treat all DateTime properties on POCO classes this way? Extension method? CustomDateTime class? Or is the only way to re-write those DateTime properties to handle MinValue? – Peter Wikström Apr 05 '11 at 13:01
  • You're welcome. Both extension methods (I like extension methods) or custom class could work. You could also make helper class with static methods for it, then have all properties use that helper. It all depends on the extent you are going to use this. I haven't looked to closely at EntityFramework but have you tried mapping the columns directly to SqlDateTime? Maybe that would be the easiest solution? – Emil Badh Apr 05 '11 at 15:50
5

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; }
}
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
dajo
  • 909
  • 10
  • 16