Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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 conversion 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...