LINQ to SQL-将日期和时间列合并为一个值

时间:2019-02-11 21:31:57

标签: asp.net linq-to-sql .net-4.6.1

我正在尝试将此SQL语句转换为LINQ:

SELECT sessionid, userid, CAST(sessiondate AS DATETIME) + CAST(sessiontime AS DATETIME) AS sessiondatetime FROM sometable

其中sessiondate的类型为DATE,而sessiontime的类型为TIME

我尝试了以下操作:

var query = from session in table
            select new
            {
              session.Id,
              session.UserId,
              DateTime = session.Date + session.Time
            };

其中tableGetTable<Session>()实例上DataContext调用的返回值,而Session类将sessionid映射到IduseridUserIdsessiondateDate(日期时间)和sessiontimeTime(时间范围)。

LINQ被翻译为以下冗长的SQL语句:

SELECT [t0].[sessionid] AS [Id], [t0].[userid] AS [UserId], CONVERT(DateTime,DATEADD(HOUR, DATEPART(HOUR, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(MINUTE, DATEPART(MINUTE, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(SECOND, DATEPART(SECOND, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(MILLISECOND, DATEPART(MILLISECOND, [t0].[sessiontime]), [t0].[sessiondate])))))))) AS [DateTime] FROM [sometable] AS [t0]

不幸的是,当尝试执行该语句时,它告诉我“数据类型为date的date函数dateadd不支持datepart毫秒”。我猜想对以毫秒为单位的DATEADD调用不满意。有办法解决这个问题吗?

编辑:请注意,session.Datesession.Time都可以为空。

1 个答案:

答案 0 :(得分:1)

不幸的数据结构使代码很丑陋:

var query = from session in table
select new
{
    session.id,
    session.userid,
    combinedDate = new DateTime(
        session.Date.Year, session.Date.Month, session.Date.Day, 
        session.Time.Hour, session.Time.Minute, session.Time.Second, 
        session.Time.Millisecond)
};