linq 无法获取要添加到日期时间的时间跨度

v440hwme  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(111)

我真的试过了,看起来很简单。
C#,使用linq.
我有一个linq查询:

var allNewStops = (from stops in rDb.DistributionStopInformations
                           where stops.CustomerNo == 91000 && stops.StopSignature != "" && stops.ActualServiceDate == dateToCheck
                           select new
                           {
                               stopName = stops.StopName,
                               signature = stops.StopSignature,
                               customerRefNumber = stops.CustomerReference,
                               dateOfStop = stops.ActualServiceDate,
                               timeOfStop = stops.ActualArrivalTime

                           }).Distinct();

这看起来工作得很好,我需要将dateOfStop与timeOfStop结合起来--最好在查询中,但之后也可以。
我试过:

DateTime combined = stopinfo.dateOfStop.Add;

但Add声明它是未知的日期时间方法
它确实显示了dateOfStop是DateTime,timeOfStop是TimeSpan。
我已经尝试了大约4打不同的组合,我能想到的一切。
我做错了什么??
谢谢你,谢谢!

nvbavucw

nvbavucw1#

从我所看到的,似乎你试图错误地使用添加添加需要一个参数(一个无参数的版本不存在)。除此之外,因为我不知道确切的数据布局,我确保在变量是对象的情况下显式地转换变量,但是如果它们已经是适当的数据类型,那么它们可以在没有(DateTime)和(TimeSpan)的情况下使用:

var allNewStops = (from stops in rDb.DistributionStopInformations
                       where stops.CustomerNo == 91000 && stops.StopSignature != "" && stops.ActualServiceDate == dateToCheck select stops)
                       .AsEnumerable().Select(stops => new {     
                           stopName = stops.StopName,
                           signature = stops.StopSignature,
                           customerRefNumber = stops.CustomerReference,
                           dateOfStop = stops.ActualServiceDate,
                           timeOfStop = stops.ActualArrivalTime,
                           combinedStop = ((DateTime)stops.ActualServiceDate).Add((TimeSpan)stops.ActualArrivalTime)

                       }).Distinct();
nqwrtyyt

nqwrtyyt2#

DateTime aNewDateTime = theOldDate.Add(aTimeSpan);
vfwfrxfs

vfwfrxfs3#

如果你的dateOfStop是DateTime类型,而timeOfStop是TimeSpan,那么像这样添加它应该没有问题:

DateTime combined = dateOfStop.Add(timeOfStop);
46scxncf

46scxncf4#

如果在任何Linq查询中调用DateTime.Add(TimeSpan),同时试图从数据库中获取,则会抛出错误。正如托马斯所建议的,你可以在进行投影之前从数据库中获取所有结果,* 或者 * 你可以使用DbFunctions.CreateDateTime函数,它告诉EF如何安全地将代码转换为SQL。以下是我的案例:

Start = DbFunctions.CreateDateTime(
    g.ScheduledDate.Year,
    g.ScheduledDate.Month,
    g.ScheduledDate.Day,
    g.WorkFrom.Value.Hours,
    g.WorkFrom.Value.Minutes,
    g.WorkFrom.Value.Seconds
)

其中g.ScheduledDateDateTimeg.WorkFromTimeSpan

相关问题