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;
开发者_如何学JAVA }
}
/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; }
}
精彩评论