【问题标题】:NHibernate how to get members who have a birthday in following n daysNHibernate如何获取在接下来的n天内过生日的成员
【发布时间】:2017-05-24 00:06:08
【问题描述】:

我的成员表有一个名为 Birthdate 的可为空的 DateTime 字段。我需要获取在接下来的 n 天内过生日的成员。我尝试了几种方法,但都没有奏效。

1

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 
    );

不能将 x.BirthDate 传递给 DateTime 构造函数

2

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

引发识别错误。

您知道任何可行且简单的方法吗?

【问题讨论】:

  • 您是否尝试过在开始过滤之前先查看GetAll() 返回的内容?

标签: c# nhibernate date


【解决方案1】:

支持DateTimeDateTimeOffset 上的一系列属性。你可以看到列表herereference documentation 有一天也会有一个专门的 Linq 部分。 (已提交,尚未发布。)

因此,猜测您的 GetAll 会产生 IQueryable,您可以这样编写查询:

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 属性。

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 2011-08-21
    • 2016-04-20
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多