可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
i have an app written for 2008.
We are using linq to entities.
We've now had to switch the DB to 2005. I am getting the following error on linq SELECT queries:
Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
The offending line is:
DateOfBirth = ((s.Date_Of_Birth == null) || (s.Date_Of_Birth <= lowdate)) ?
DateTime.MinValue : s.Date_Of_Birth.Value,
DateOfBirth is of type DateTime and a property in our own business object (not entity).
Anyone know how i can modify this line to make this query run?
回答1:
Make sure that lowdate
is at least 1/1/1753.
If you try to supply a date prior to that, EF will convert it, and pass it into your query. In addition, you need to not use DateTime.MinValue
in the query, but rather what would be your min:
DateOfBirth = ((s.Date_Of_Birth == null) || (s.Date_Of_Birth <= lowdate)) ?
new DateTime(1753,1,1) : s.Date_Of_Birth.Value;
Remember, with EF, the query gets compiled and converted to SQL on the server, so the values must all be appropriate there, as well.
That being said, I'd personally prefer to store DateOfBirth
as DateTime?
(nullable type) instead of using a "magic value" (DateTime.MinValue
) to hold database null or inappropriate values.
回答2:
Also, just to add to the good answers here, try using SqlDateTime.MinValue instead of 1/1/1973 or DateTime.MinValue.
http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.minvalue.aspx
Sure, it's the same thing as 1/1/1973, but it's a lot cleaner and a lot less magical.
回答3:
Try using (DateTime)SqlDateTime.MinValue
instead:
DateOfBirth = ((s.Date_Of_Birth == null) || (s.Date_Of_Birth <= lowdate)) ?
(DateTime)SqlDateTime.MinValue : s.Date_Of_Birth.Value,
You will need to include:
using System.Data.SqlTypes;
That will take care of the issue if you still want to use a non-null date field. However, as others have mentioned, it may be better to go with a null date field.
回答4:
The DateTime.MinValue
is equivalent to 00:00:00.0000000, January 1, 0001
.
And the DateTime in SQL 2005 is between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 P
Instead of using DateTime.MinValue, You should create a
public static DateTime DateTimeMinValueInSQL2005 = new DateTime(1753,1,1);
and use it instead DateTime.MinValue;
回答5:
This often happens when you try to persist DateTime.MinValue to a SQL DateTime field
回答6:
Sure, replace DateTime.MinValue with "1/1/1753 12:00:00 AM"
回答7:
I've created an extension function for this:
/// <summary>
/// Will return null if the CLR datetime will not fit in an SQL datetime
/// </summary>
/// <param name="datetime"></param>
/// <returns></returns>
public static DateTime? EnsureSQLSafe(this DateTime? datetime)
{
if (datetime.HasValue && (datetime.Value < (DateTime)SqlDateTime.MinValue || datetime.Value > (DateTime)SqlDateTime.MaxValue))
return null;
return datetime;
}