2013-10-11 26 views
0

我有一个WCF服务,这应该从一个范围返回最大日志日期为特定的机器,或返回null如果该机器没有任何日志条目:什么是正确的方式返回在C#中的可空日期?

public DateTime? GetLastBootEvent(string laptopName) 
    { 
     ITDashboardDataContext itdb = new ITDashboardDataContext(); 

     DateTime? latestEvent = (from be in itdb.tl_sta_bootTimes 
         where be.machineName.ToUpper() == laptopName.ToUpper() 
         select be.timestamp 
         ).Max(); 

     return latestEvent; 

    } 

然而,当我运行它,我得到出现以下错误:

"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs."

那里没有太多的信息。我认为通过使用DateTime?而不是DateTime这应该允许返回空值?

我可以通过返回过去一些随机日期的方法来处理这个问题,比如MinDate,但是我想干净地这样做。

+5

你可以打开跟踪来查看错误http://stackoverflow.com/questions/4271517/how-to-turn-on-wcf-tracing代码看起来不错,我会做一个疯狂的猜测,并说收集有没有元素和最大thorws异常 – wiero

+1

返回可以为空的DateTime在wcf – Szymon

+0

中完全正常我没有看到任何理由认为错误与可空类型有关。 –

回答

1

你需要在查询中投的时间戳可为空的日期时间即

DateTime? latestEvent = (from be in itdb.tl_sta_bootTimes 
         where be.machineName.ToUpper() == laptopName.ToUpper() 
         select (DateTime?)be.timestamp 
         ).Max(); 
+0

如果时间戳不是DateTime?代码已经不能编译了。 –

1

听起来像你想在这里使用DefaultIfEmpty例如,

DateTime? latestEvent = (from be in itdb.tl_sta_bootTimes 
         where be.machineName.ToUpper() == laptopName.ToUpper() 
         select be.timestamp 
         ).DefaultIfEmpty(null).Max(); 

如果没有记录Max会在没有记录的情况下抛出异常。

相关问题