开发者

An overflow occurred while converting to datetime using EF4

I have a windows application working with a SQL Compact 4.0 database, using EF 4.1 and code-first approach. I cannot save an object to the database since I'm getting an exception, with inner exception "An overflow occurred while converting to datetime" when trying to save the type Quotation:

public class Quotation
{
    public int ID { get; set; }

    public string Name { get; set; }

    public DateTime DateCreated { get; set; }

    public ContactPerson ContactPersonAssigned { get; set; }

    public string OurReference { get; set; }

    public string QuotationDataString { get; set; }
}

I read that this error can be caused by a mismatch between my application settings and the sql compact database settings regarding the conversio开发者_StackOverflow社区n of a date. I'm not sure about it, since my sdf database file has a field which is correctly named "DateCreated", not-nullable and of type "datetime".

I'm new to SQL compact. Could you help me debug this problem?


If your model has non-nullable property of type DateTime, when you post a form with empty value for that property, it is automatically set to DateTime.MinValue, which is in .net 01/01/0001 (DateTime.MinValue on MSDN)

(As a side note, you can change this behavior by implementing your own IModelBinder for DateTime which could i.e. throw a validation exception if attempted value is null/empty and property is not nullable).

If you try to save that value (DateTime.MinValue) into database, you will get conversion error if database field is of sql type datetime, because .net DateTime.MinValue is less than SQL datetime minvalue (01/01/1753) and therefore cannot be converted to sql value. (SQL datetime min value on MSDN)

This error will not occur on newer versions of MS SQL Server, which have datetime2 datatype which allows values from 01/01/0001 to 31/12/9999 (SQL datetime2 on MSDN) (if datetime2 is used for that field, of course).


This is an old question ... but maybe somebody could find this helpful:

I solved the problem (MVC4, EF5, SqlServerCE 4.0) using following definition:

public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }

Have fun!


I hade the same issue, the dateTime propety being saved on an object to the database was null initially.

Verify that an actually datetime has been assigned before saving the object to the local CE database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜