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

问题描述 投票:0回答: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
            };

其中table是在GetTable<Session>()实例上DataContext调用的返回值,Session类将sessionid映射到IduseridUserIdsessiondateDate(DateTime),sessiontimeTime(TimeSpan)。

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]

不幸的是,当试图执行该语句时,它告诉我“数据类型日期的日期函数dateadd不支持datepart毫秒”。我猜它对毫微秒的DATEADD调用不满意。有没有办法解决这个问题?

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

asp.net linq-to-sql .net-4.6.1
1个回答
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)
};
© www.soinside.com 2019 - 2024. All rights reserved.