2012-02-18 35 views
1

如何使用Linq查詢返回DateTimeOffset。 我需要從類型的DateTimeOffset的表截止日期如何使用Linq返回DateTimeOffset類型

public DateTimeOffset GetLastDate(Guid Id, Guid AppId)      
{ 
    var q = from k in context.Inspections 
      where k.Id == Id || k.AppId == AppId 
      select k.Duedate; 
    return q; 
} 

不能隱式轉換system.Linq.IQueryable到System.DateTimeOffset

回答

2

的問題是,您的查詢將返回一個IQueryable<T>,與類型是Duedate的類型。

如果DuedateDateTimeOffset,你可以返回的第一個結果(在哪裏可以返回多個匹配)通過:

var q = from k in context.Inspections 
      where k.Id== Id||k.AppId== AppId 
      select k.Duedate; 
    DateTimeOffset? value = q.First(); 

    if (value.HasValue) 
     return value.Value; 
    else // found NULL in DB! Do something in this case... 
     throw new ApplicationException("Null offset found"); 

    // Alternatively, you could use some default value (this uses "Now"): 
    // return value ?? DateTimeOffset.Now; 
+0

最好使用'。單()'如果你想確保你只有一次結果,或者使用'orderby'來控制你得到的多個結果中的哪一個。 – hvd 2012-02-18 00:22:16

+0

與它說..不能隱式轉換system.DateTimeOffset?到System.DateTimeOffSet ....我怎樣才能返回日期 – GANI 2012-02-18 00:24:53

+0

@ hvd取決於什麼是「更好」在這種情況下 - 非常不同的行爲,都不一定是正確的。 – 2012-02-18 00:43:07