Search code examples
c#linqdynamicentity-framework-coresystem.linq.dynamic

System.Linq.Dynamic.Core Date is empty & Date is not empty


How to do this Date is empty & Date is not empty in System.Linq.Dynamic.Core, I am currently doing this that is not working:

if (filter.Operator.StartsWith("is empty") ||
     filter.Operator.StartsWith("is not empty"))
 {
     filterOp = filter.Operator.StartsWith("is not") ? "!=" : "==";
     qs = $"{filter.Column.PropertyName} {filterOp} ''";
 }
 query = query.Where(qs);

Solution

  • Answering bunch of your questions to help your job done this year.

    1. is it possible to convert lambda function to string for use in system.linq.dynamic.core expression

    2. How to convert Func<T, bool> to Expression<Func<T, bool>>

    MudBlazor already can build filter expression and no additional crutches like Dynamic.LINQ are needed. I have checked this code and it should work with EF Core.

    There is function:

    public static class FilterExpressionGenerator
    {
        public static Expression<Func<T, bool>> GenerateExpression<T>(IFilterDefinition<T> filter, FilterOptions? filterOptions)
        ...
    

    So, basically you can use this function in the following way:

    query = query.Where(FilterExpressionGenerator.GenerateExpression<GreenPaperItem>(filter));
    

    And if you have list of these defintitions, you can create helper function which apply this list to any IQueryable

    public static class MudBlazorFilterHelper
    {
        public static IQueryable<T> ApplyFilter<T>(this IQueryable<T> query, IEnumerable<IFilterDefinition<T>> filterDefinitions)
        {
            foreach(var filter in filterDefinitions)
            {
                query = query.Where(FilterExpressionGenerator.GenerateExpression<T>(filter));
            }
            return query;
        }
    }
    

    Answering the following comment:

    but for checking that it is not enumerable at the end, I get the error "The given 'IQueryable' does not support generation of query strings." when I want to convert the query ToQueryString()

    Extension method ToQueryString() you can call ONLY when IQueryable started from DbSet, it is not applicable to IQueryable created from IEnumerable by calling AsQueryable(). These IQueryable has different Provider and ToQueryString() expects that this provider is specific EF Core provider.