2017-05-23 9 views
1

メンバーテーブルのBirthdateという名前のnull可能なDateTimeフィールドがあります。私は次のn日に誕生日のあるメンバーを取得する必要があります。私はいくつかの方法を試しましたが、どれも働いていませんでした。NHibernate n日後に誕生日を持つメンバーを取得する方法

DateTime startDate = DateTime.Now; 
DateTime endDate = DateTime.Now.AddDays(n); 

GetAll().Where(
    x => x.BirthDate != null 
    && new DateTime(startDate.Year, x.BirthDate.Value.Month, x.BirthDate.Value.Day, 1, 1, 1) >= startDate 
    && new DateTime(endDate.Year, x.BirthDate.Value.Month, x.BirthDate.Value.Day, 1, 1, 1) <= endDate 
    ); 

のDateTimeコンストラクタ

GetAll().OrderByDescending(m => m.CreateDate) 
    .Where(x => x.BirthDate.HasValue 
     && (endDate - x.BirthDate.Value).Days <= n) 

にx.BirthDateを渡すことはできません認識エラーをスロー。

これを行うにはどの作業方法も簡単ですか?

+0

フィルタリングを開始する前に 'GetAll()'が返すものをまず調べてみましたか? – yoger

答えて

0

は、DateTimeDateTimeOffsetのプロパティの束をサポートしています。リストhereが表示されます。 reference documentationでもいつか専用のLinqセクションがあります。 (すでにコミット、まだリリースされていない。)

ので、GetAllIQueryableをもたらし、あなたの推測、あなたは道クエリ書くことができます:

var startDate = DateTime.Now; 
var endDate = DateTime.Now.AddDays(n); 
if (startDate.Year == endDate.Year) 
{ 
    // Simple case, just compare months and days. 
    GetAll().Where(
     x => x.BirthDate.Value.Month >= startDate.Month && 
      x.BirthDate.Value.Day >= startDate.Day && 
      x.BirthDate.Value.Month <= endDate.Month && 
      x.BirthDate.Value.Day <= endDate.Day); 
} 
else 
{ 
    // Range spanning two distinct years, so matching dates 
    // are either lower months and days than endDate, OR 
    // greater months and days than startDate. (Cannot have both.) 
    GetAll().Where(
     x => x.BirthDate.Value.Month >= startDate.Month && 
      x.BirthDate.Value.Day >= startDate.Day || 
      x.BirthDate.Value.Month <= endDate.Month && 
      x.BirthDate.Value.Day <= endDate.Day); 

} 

は私がHasValueのチェックを削除したのクエリが翻訳されている場合この場合、SQLにはSQLは必要ありません。

私はそれが同じDateTimeプロパティをサポートしていると信じていますが、それはでも同じです。

関連する問題