Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LINQ Expression Trees Support #54

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>net6.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>
Expand Down Expand Up @@ -48,12 +48,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.6.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.1" />
<PackageReference Include="nunit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="FluentAssertions" Version="6.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.1" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion ExpressionBuilder.Test/Database/BuilderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#if (NETSTANDARD2_0 || NETSTANDARD2_1 || NETSTANDARD2_2 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2)
#if (NETSTANDARD2_0 || NETSTANDARD2_1 || NETSTANDARD2_2 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NET6_0_OR_GREATER)

using ExpressionBuilder.Test.NetCore.Database;

Expand Down
1 change: 1 addition & 0 deletions ExpressionBuilder.Test/ExpressionBuilder.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
<Compile Include="Database\BuilderTest.cs" />
<Compile Include="Database\Northwind.cs" />
<Compile Include="Integration\BuilderTest.cs" />
<Compile Include="Integration\GroupBuilderTest.cs" />
<Compile Include="Integration\OperationTests.cs" />
<Compile Include="Integration\PropertyLoaderTest.cs" />
<Compile Include="Models\Contact.cs" />
Expand Down
110 changes: 110 additions & 0 deletions ExpressionBuilder.Test/Integration/GroupBuilderTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
using ExpressionBuilder.Builders;
using ExpressionBuilder.Common;
using ExpressionBuilder.Generics;
using ExpressionBuilder.Operations;
using ExpressionBuilder.Test.Models;
using ExpressionBuilder.Test.Unit.Helpers;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionBuilder.Test.Integration
{
[TestFixture]
public class GroupBuilderTest
{
private List<Person> _people;

public List<Person> People
{
get
{
if (_people == null)
{
_people = new TestData().People;
}

return _people;
}
}

[TestCase(TestName = "Passing null filter should return true")]
public void GroupWithEmptyFilter()
{
var expr1 = GroupBuilder.GetFilter<Person>(null);
Assert.AreEqual(expr1.Invoke(null), true);
var expr2 = GroupBuilder.GetFilter<Person>(new Filter<Person>());
Assert.AreEqual(expr2.Invoke(null), true);
}

[TestCase(TestName = "Passing null array should return true")]
public void GroupWithEmptyFilterArray()
{
var andExpression = GroupBuilder.GetFilter(GroupBuilder.Group<Person>(Common.Connector.And, null));
var orExpression = GroupBuilder.GetFilter(GroupBuilder.Group<Person>(Common.Connector.Or, null));
Assert.AreEqual(andExpression.Invoke(null), true);
Assert.AreEqual(orExpression.Invoke(null), true);
Assert.AreEqual(andExpression.Invoke(null), orExpression.Invoke(null));
}

[TestCase(TestName = "1 passed filter should return that filter's expression")]
public void GroupWithSingleElementFilterArray()
{
var filter = new Filter<Person>();
filter.By("Birth.Country", Operation.IsEmpty, null, (object)null, Connector.And);
var andExpression = GroupBuilder.GetFilter(GroupBuilder.Group<Person>(Common.Connector.And, filter));
var orExpression = GroupBuilder.GetFilter(GroupBuilder.Group<Person>(Common.Connector.Or, filter));
var people1 = People.Where(andExpression);
var solution = People.Where(filter);
Assert.That(people1, Is.EquivalentTo(solution));
var people2 = People.Where(orExpression);
Assert.That(people2, Is.EquivalentTo(solution));
}

[TestCase(TestName = "And/Or with 2 parameters")]
public void GroupWith2Parameters()
{
var f1 = new Filter<Person>();
f1.By("Birth.Date", Operation.IsNotNull);
var f2 = new Filter<Person>();
f2.By("Birth.Date", Operation.GreaterThan, new DateTime(1980, 1, 1));
var orExpression = Connector.Or.Group<Person>(f1, f2).GetFilter();
var orPeople = People.Where(orExpression);
var orFilter = new Filter<Person>();
orFilter.By("Birth.Date", Operation.IsNotNull).Or.By("Birth.Date", Operation.GreaterThan, new DateTime(1980, 1, 1));
var orSolution = People.Where(orFilter);
Assert.That(orPeople, Is.EquivalentTo(orSolution));

var andExpression = Connector.And.Group<Person>(f1, f2).GetFilter();
var andPeople = People.Where(andExpression);
var andFilter = new Filter<Person>();
andFilter.By("Birth.Date", Operation.IsNotNull).And.By("Birth.Date", Operation.GreaterThan, new DateTime(1980, 1, 1));
var andSolution = People.Where(andFilter);
Assert.That(andPeople, Is.EquivalentTo(andSolution));
}

[TestCase(TestName = "Group equal to builder using complex expressions (fluent interface)", Category = "ComplexExpressions")]
public void GroupUsingComplexExpressionsFluentInterface()
{
var f1 = new Filter<Person>();
var f2 = new Filter<Person>();
var f3 = new Filter<Person>();
var f4 = new Filter<Person>();
f1.By("Birth.Country", Operation.EqualTo, "USA");
f2.By("Name", Operation.DoesNotContain, "doe");
f3.By("Name", Operation.EndsWith, "Doe");
f4.By("Birth.Country", Operation.IsNullOrWhiteSpace);
var orExpression = Connector.Or.Group(Connector.And.Group<Person>(f1, f2), Connector.And.Group<Person>(f3, f4)).GetFilter();
var people = People.Where(orExpression);
var filter = new Filter<Person>();
filter.By("Birth.Country", Operation.EqualTo, "USA").And.By("Name", Operation.DoesNotContain, "doe")
.Or
.Group.By("Name", Operation.EndsWith, "Doe").And.By("Birth.Country", Operation.IsNullOrWhiteSpace);
var solution = People.Where(filter);
Assert.That(people, Is.EquivalentTo(solution));
}
}
}
66 changes: 66 additions & 0 deletions ExpressionBuilder/Builders/GroupBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using ExpressionBuilder.Common;
using ExpressionBuilder.Interfaces;
using System;
using System.Linq.Expressions;

namespace ExpressionBuilder.Builders
{
/// <summary>
/// Static class that enables creating LINQ expression trees.
/// </summary>
public static class GroupBuilder
{
/// <summary>
/// Combines zero or more LINQ Expressions into a single LINQ Expression.
/// Return true if no filters are supplied.
/// </summary>
/// <typeparam name="TClass"></typeparam>
/// <param name="connector"></param>
/// <param name="filters">The LINQ expressions to combine.</param>
/// <returns>Single combined LINQ expression.</returns>
public static Expression<Func<TClass, bool>> Group<TClass>(this Connector connector, params Expression<Func<TClass, bool>>[] filters) where TClass : class
{
if (filters == null)
{
return (c) => true;
}
if (filters.Length == 1)
{
return filters[0];
}
Expression<Func<TClass, bool>> predicate = null;
if (connector == Connector.And)
{
predicate = c => true;
foreach (var filter in filters)
{
predicate = predicate.And(filter);
}
}
else if (connector == Connector.Or)
{
predicate = c => false;
foreach (var filter in filters)
{
predicate = predicate.Or(filter);
}
}
return predicate;
}

/// <summary>
/// Converts a LINQ expression to a lambda delegate.
/// </summary>
/// <typeparam name="TClass"></typeparam>
/// <param name="filter">The expression to compile</param>
/// <returns>The function that can be used inside LINQ functions (e.g. Where, Any, ...).</returns>
public static Func<TClass, bool> GetFilter<TClass>(this Expression<Func<TClass, bool>> filter) where TClass : class
{
if (filter == null)
{
return (c) => true;
}
return filter.Compile();
}
}
}
13 changes: 13 additions & 0 deletions ExpressionBuilder/Common/CommonExtensionMethods.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

Expand Down Expand Up @@ -76,5 +77,17 @@ public static bool IsGenericList(this object o)
var oType = o.GetType();
return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List<>)));
}

public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}
17 changes: 11 additions & 6 deletions ExpressionBuilder/ExpressionBuilder.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net452</TargetFrameworks>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<Authors>David Belmont</Authors>
<RepositoryUrl>https://github.com/dbelmont/ExpressionBuilder</RepositoryUrl>
<PackageIconUrl>https://raw.githubusercontent.com/dbelmont/ExpressionBuilder/master/ExpressionBuilder/ExpressionBuilder.png</PackageIconUrl>
Expand All @@ -19,9 +19,11 @@

Useful to turn WebApi requests parameters into expressions, create advanced search screens with the capability to save and re-run those filters, among other things.
</Description>
<AssemblyVersion>2.1.0.0</AssemblyVersion>
<AssemblyVersion>2.1.0.2</AssemblyVersion>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Version>2.1.0-rc</Version>
<Version>2.1.4</Version>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageId>LambdaExpressionBuilder</PackageId>
</PropertyGroup>
Expand All @@ -30,16 +32,16 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Extensions.Configuration.Binder">
<Version>2.2.0</Version>
<Version>6.0.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.Json">
<Version>2.2.0</Version>
<Version>6.0.0</Version>
</PackageReference>
<PackageReference Include="System.Configuration.ConfigurationManager">
<Version>4.5.0</Version>
</PackageReference>
<PackageReference Include="System.ComponentModel.Annotations">
<Version>4.5.0</Version>
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
Expand All @@ -63,4 +65,7 @@
<PackagePath></PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion ExpressionBuilder/Generics/Filter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace ExpressionBuilder.Generics
public class Filter<TClass> : IFilter, IXmlSerializable where TClass : class
{
private readonly List<List<IFilterStatement>> _statements;

public IFilter Group
{
get
Expand Down
Loading