Compare commits

...

2 Commits

3 changed files with 43 additions and 10 deletions

View File

@ -144,6 +144,20 @@ public class PagedRequestTests {
Assert.Single(filtered); // Assuming only "John" starts with "Jo"
}
[Fact]
public void BuildFilterExpression_ShouldHandleEqualsAndContainsOperators() {
var queryable = GetTestQueryable();
var request = new PagedRequest {
Filters = "Age == \"31\" && (Name.Contains(\"Jo\"))"
};
var predicate = request.BuildFilterExpression<TestEntity>();
var filtered = queryable.Where(predicate).ToList();
Assert.Contains(filtered, t => t.Name.StartsWith("Jo"));
Assert.Single(filtered); // Assuming only "John" starts with "Jo"
}
[Fact]
public void BuildFilterExpression_ShouldHandleEndsWithOperator() {
var queryable = GetTestQueryable();

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata -->
<PackageId>MaksIT.Core</PackageId>
<Version>1.3.1</Version>
<Version>1.3.3</Version>
<Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company>
<Product>MaksIT.Core</Product>

View File

@ -15,16 +15,35 @@ public class PagedRequest : RequestModelBase {
if (string.IsNullOrWhiteSpace(Filters))
return x => true; // Returns an expression that doesn't filter anything.
// Adjust Filters to make Contains, StartsWith, EndsWith, ==, and != case-insensitive
string adjustedFilters = Filters
.Replace(".Contains(", ".ToLower().Contains(")
.Replace(".StartsWith(", ".ToLower().StartsWith(")
.Replace(".EndsWith(", ".ToLower().EndsWith(")
.Replace("==", ".ToLower() ==")
.Replace("!=", ".ToLower() !=");
// Get the type of T
var type = typeof(T);
// Ensure values are also transformed to lowercase
adjustedFilters = Regex.Replace(adjustedFilters, "\"([^\"]+)\"", m => $"\"{m.Groups[1].Value.ToLower()}\"");
// Adjust Filters to make Contains, StartsWith, EndsWith, ==, and != case-insensitive
string adjustedFilters = Filters;
// Regex to find property names and methods
adjustedFilters = Regex.Replace(adjustedFilters, @"(\w+)\.(Contains|StartsWith|EndsWith)\(\""(.*?)\""\)", m => {
var propertyName = m.Groups[1].Value;
var method = m.Groups[2].Value;
var value = m.Groups[3].Value;
var property = type.GetProperty(propertyName);
if (property != null && property.PropertyType == typeof(string)) {
return $"{propertyName}.ToLower().{method}(\"{value.ToLower()}\")";
}
return m.Value;
});
// Regex to find equality and inequality comparisons
adjustedFilters = Regex.Replace(adjustedFilters, @"(\w+)\s*(==|!=)\s*\""(.*?)\""", m => {
var propertyName = m.Groups[1].Value;
var comparison = m.Groups[2].Value;
var value = m.Groups[3].Value;
var property = type.GetProperty(propertyName);
if (property != null && property.PropertyType == typeof(string)) {
return $"{propertyName}.ToLower() {comparison} \"{value.ToLower()}\"";
}
return m.Value;
});
// Parse the adjusted filter string into a dynamic lambda expression
var predicate = DynamicExpressionParser.ParseLambda<T, bool>(