Linq声明在哪里

时间:2013-11-22 08:53:11

标签: linq

我正在构建一个查询工具,供非技术人员用来从数据库中检索记录。

我有一个包含各种下拉菜单的表单,用户可以根据他们要查找的内容进行选择。

我遇到了一个问题,即我的查询返回的记录与用户选择不匹配。

我相信只有在我查询连接表时才会发生这种情况。

我有以下内容:

results = results.Where(c => c.CustomerEnrollment
                  .Where(x => x.CustomerCategoryID == CustomerCategoryID)
                  .Any());

results = results.Where(c => c.CustomerEnrollment
              .Where(x => x.StartDate <= DateRangeStart && x.EndDate >= DateRangeStart)
              .Any());

这将返回正确类别的结果,但不会在指定的日期范围内。

我也尝试过:

results = results.Where(c => c.CustomerEnrollment
                          .Any(x => x.CustomerCategoryID == CustomerCategoryID));

2 个答案:

答案 0 :(得分:2)

尝试将日期范围检查更改为;

变化:

x => x.StartDate <= DateRangeStart && x.EndDate >= DateRangeStart

要:

//StartDate should be greater than or equal to
//EndDate should be less than or equal to
//Also you are using same variable DateRangeStart to check start and end
x => x.StartDate >= DateRangeStart && x.EndDate <= DateRangeEnd

答案 1 :(得分:0)

您的查询会返回包含任何CustomerEnrollment个ID的类别,并且在所需数据范围内也有CustomerEnrollment,但这些CustomerEnrollment s 不一定是相同

要确保您获得的CustomerEnrollment类别符合您必须满足的两个条件:

results = results.Where(c => c.CustomerEnrollment
                  .Where(x => x.CustomerCategoryID == CustomerCategoryID
                           && x.StartDate <= DateRangeStart
                           && x.EndDate >= DateRangeStart)
                  .Any());

使用PredicateBuilder,您可以参数化条件:

using LinqKit;
...

var pred = Predicate.True<CustomerEnrollment>();

if (CustomerCategoryID > 0)
    pred = pred.And(c => c.CustomerCategoryID == CustomerCategoryID);

if (DateRangeStart.HasValue)
    pred = pred.And(c => c.StartDate <= DateRangeStart
                      && c.EndDate >= DateRangeStart);

results = results.AsExpandable()
                 .Where(c => c.CustomerEnrollment.AsQueryable()
                     .Any(pred));

.AsExpandable().AsQueryable()的组合似乎是避免例外的唯一方法。