正确筛选林克查询



我有一个查询,它从一堆商店中检索销售,并将它们作为列表返回。在我的报告请求屏幕上,用户可以按多个 ID 进行筛选 - ShopOwnerId、ShopRegionId、ShopTypeCode 等。

我的查询结构是获取所选日期之间的所有销售,然后根据选择进行筛选。这显然是非常低效的。:

private List<Sales> GetFilteredListOfSales(Request reportreq)
{
    ModelContainer ctn = new ModelContainer();
    List<ShopSale> shopsSales = new List<shopsale>();
    // If no filters are selected
    //
    if (reportreq.RegionalId == null && reportreq.OwnerId == null && reportreq.ShopTypeCode == null)
    {
        shopsSales = (from sale in ctn.ShopSales
                    where sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
                    select sale).ToList();
    }

    // If the regional ID has a value...
    // 
    if (reportreq.RegionalId.HasValue)
    {
        shopsSales = (from sale in ctn.ShopSales
                  where sale.Shop.Owner.RegionalId == reportreq.RegionalId
                    && sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
                  select sale).ToList();
    }
    // If the owner ID has a value...
    // 
    if (reportreq.OwnerId.HasValue)
    {
        shopsSales = (from sale in ctn.ShopSales
                  where sale.Shop.OwnerId == reportreq.OwnerId
                    && sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
                  select sale).ToList();
    }
    if (!string.IsNullOrEmpty(reportreq.ShopTypeCode))
    {
        shopsSales = (from sale in ctn.ShopSales
                  where sale.Shop.ShopTypeCode.ToUpper().Contains(reportreq.ShopTypeCode.ToUpper())
                    && sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
                  select sale).ToList();
    }

    return shopsSales;
}

您可以看到,此方法仅在未选择筛选器的情况下查询特定日期之间的销售表。

我坚持的是,用户可以选择多个过滤器 - 例如,他们可能会选择一个regionId和一个ShopTypeCode,所以我不想查询ctn。每个 if 过滤器的 ShopSales,因为如果选择了多个值,它将清除以前检索到的值。

有人对如何解决这个问题有任何建议吗?如果需要更多信息,请询问!

谢谢

当然 - 您不希望每次都从头开始构建查询。只需有条件地添加额外的Where调用:

var query = ctn.ShopSales.Where(sale => sale.DateSold >= reportreq.FromDate 
                                     && sale.DateSold <= reportreq.ToDate);
if (reportreq.OwnerId.HasValue)
{
    query = query.Where(sale => sale.Shop.OwnerId == reportreq.OwnerId);
}
if (!string.IsNullOrEmpty(reportreq.ShopTypeCode))
{
    query = query.Where(sale.Shop.ShopTypeCode.ToUpper()
                            .Contains(reportreq.ShopTypeCode.ToUpper());
}
var shopSales = query.ToList();

请注意,在最后一行具体化查询之前,查询不会执行

相关内容

  • 没有找到相关文章

最新更新