LINQ Option内置查询+日期时间比较



这个简单的查询工作并返回预期的4条记录;

var showIfAfter = DateTime.Now.AddDays(-1);
var query = _context.OTMLessons.Where(l => l.Date > showIfAfter);

这个逐段构建的查询没有(假设状态==A(;

var query = _context.OTMLessons.Include("Years").Include("Giver")
    .Where(l => !l.Hidden);
if (status != null)
    switch (status) {
        case "A":
            // only records that are current (last day plus important states)
            var showIfAfter = DateTime.Now.AddDays(-1);
            query = query.Where(l => l.Date > showIfAfter);
            break;
        case "ND":
            // only records which aren't deleted
            query = query.Where(l => !l.Status.Equals("Deleted"));
            break;
        default:
            // records of a specific state
            query = query.Where(l => l.Status.Equals(status));
            break;
    }

请告诉我为什么我是个白痴——把我的头发拔出来。。。

我相信您的问题在Include()中。

var query = _context.OTMLessons.Where(l => !l.Hidden);
if (status != null)
    switch (status) {
        case "A":
            // only records that are current (last day plus important states)
            var showIfAfter = DateTime.Now.AddDays(-1);
            query = query.Where(l => l.Date > showIfAfter).Include("Years").Include("Giver");
            break;
        case "ND":
            // only records which aren't deleted
            query = query.Where(l => !l.Status.Equals("Deleted")).Include("Years").Include("Giver");
            break;
        default:
            // records of a specific state
            query = query.Where(l => l.Status.Equals(status)).Include("Years").Include("Giver");
            break;
    }

可能看起来有点冗长;但是一旦计算出日期/状态字段,它就应该包括子集集合。

您的两个查询不同。第一个说:

_context.OTMLessons.Where(l => l.Date > showIfAfter);

第二条说(最终:

_context.OTMLessons.Include("Years").Include("Giver")
.Where(l => !l.Hidden && l.Date > showIfAfter);

您应该检查是哪个差异导致了结果的变化。首先尝试使它们完全相同,然后开始添加更多的标准。然后,您可以检查结果的变化,并验证您的数据。

相关内容

  • 没有找到相关文章

最新更新