我有三个过滤器,分别是类别,子类别和产品类型,需要应用于搜索查询。我目前正在使用Azure搜索。到目前为止,我正在使用odata过滤器,如下面的代码所示。
SearchParameters parameters = new SearchParameters();
string searchText = Request.Query["query"];
string category = Request.Query["c"];
string subCategory = Request.Query["sc"];
string productType = Request.Query["pt"];
parameters.Filter = $"Category/Id eq '{category}' or SubCategory/Id eq '{subCategory}'" +
$"or ProductType/Id eq '{productType}'";
我如何获得一个结果,如果用户应用categoryId,那么它应该显示与该类别ID有关的结果。如果用户同时应用categoryId和subcategoryId,则他应该能够看到与指定过滤器匹配的两种产品类别和子类别。如果仅提交producttypeId,则他应该能够看到与该producttypeId相关的产品。当然,我可以使用if和else并使用'logical or'和'logical and'构建过滤器。是否有任何Odata库在这方面对我有帮助?
您不能执行以下操作吗?
string category = Request.Query["c"];
string subCategory = Request.Query["sc"];
string productType = Request.Query["pt"];
string categoryQuery = string.isNullOrWhiteSpace(category) ? "('1' eq '1')" : $"(Category/Id eq '{category}')";
string subCategoryQuery = string.isNullOrWhiteSpace(subCategory) ? "('1' eq '1')" : $"(SubCategory/Id eq '{subCategory}')";
string productTypeQuery = string.isNullOrWhiteSpace(productType) ? "('1' eq '1')" : $"(ProductType/Id eq '{productType}')";
parameters.Filter = $"{categoryQuery} and {subCategoryQuery} and {productTypeQuery}";
感谢您的建议。我使用OData FilterString解决了这一问题的方法
string filterquery = FilterString.Generate<Product>(p => p.Category.Id == category &&
p.SubCategory.Id == subCategory &&
p.ProductType.Id == productType);
parameters.Filter = filterQuery;