5

当我的数据库中有闰年时(例如:2012 年 2 月 29 日)。EntityFunctions.CreateDateTime 函数抛出System.Data.SqlClient.SqlException: Conversion failed when converting date and/or time from character string.

我的代码在我的 asp.net mvc (C#) 应用程序中如下所示:

from u in _entities.tt_Users
let _start_date = u.Start_Date
let _startDate = _start_date.Day
let _startmonth = _start_date.Month
let _startyear = _start_date.Year
let _starthour = u.Start_Time.Value.Hours
let _startminutes = u.Start_Time.Value.Minutes
let _startseconds = u.Start_Time.Value.Seconds
let _startDateWithTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, _starthour, _startminutes, _startseconds)
let _startDateWithZeroTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, 0, 0, 0)
let _start_datetime = u.Is_Include_Time ? _startDateWithZeroTime : _startDateWithTime
let _end_date = u.End_Date
let _endDate = _end_date.Day
let _endmonth = _end_date.Month
let _endyear = _end_date.Year
let _endhour = u.End_Time.Value.Hours
let _endminutes = u.End_Time.Value.Minutes
let _endseconds = u.End_Time.Value.Seconds
let _endDateWithTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, _endhour, _endminutes, _endseconds)
let _endDateWithZeroTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, 0, 0, 0)
let _end_datetime = u.Is_Include_Time ? _endDateWithZeroTime : _endDateWithTime
let _cur_Start_date = u.Is_Include_Time ? _userStartDate : _gMTStartDate
let _cur_End_date = u.Is_Include_Time ? _userEndDate : _gMTEndDate
where u.User_Id == 1 && !u.Is_Deleted
&& _start_datetime >= _cur_Start_date && _end_datetime <= _cur_End_date
select new
{
  u.User_id,
  u.User_Name,
  u.Login_Name,
  u.Email_Address
};

这里 _userStartDate、_userEndDate、_gMTStartDate 和 _gMTEndDate 是我函数的参数。

如果“Is_Include_Time”列为真,那么我还必须从表中包含 TimeSpan。但是对于闰年它抛出了错误。

有什么建议么?

4

3 回答 3

2

我刚刚遇到了同样的问题。我在数据库行中有一些值需要转换为日期时间。我发现我可以使用以下构造:

            DateTime startDate = new DateTime(1, 1, 1);
            var counters = from counter in entities.Counter
                           let date = SqlFunctions.DateAdd("day", counter.DayOfMonth-1, SqlFunctions.DateAdd("month", counter.Month-1, SqlFunctions.DateAdd("year", counter.Year-1, startDate)))
                           where date >= dateFrom && date <= dateTo
                           orderby date
                           select new
                           {
                               Value = counter.CounterValue,
                               Date = date
                           };

我不确定性能影响,但它确实有效。

最好的问候, Tor-Odd

于 2012-03-05T12:30:36.810 回答
0

这是我处理的方式

var minDate = Convert.ToDateTime("1900-01-01 00:00:00");
return source.Where(x => EntityFunctions.DiffDays(x.ReviewedDate, minDate) > 0).ToList();
于 2012-05-25T04:33:00.337 回答
0

尝试按照我在这里的建议在 linq 表达式之外使用声明的变量

于 2012-02-29T11:47:29.467 回答