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
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;
}
}
}
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With