enisn / AutoFilterer

AutoFilterer is a mini filtering framework library for dotnet. The main purpose of the library is to generate LINQ expressions for Entities over DTOs automatically. The first aim is to be compatible with Open API 3.0 Specifications
MIT License
463 stars 37 forks source link

[Q] Range doesn't include null fields in database #22

Closed enisn closed 3 years ago

enisn commented 3 years ago

Problem

By default, Range<T> doesn't include null values, it generates only GTE (>=) and LTE (<=) comparison. So null values don't match these arithmetic comparison because they're not greater or lesser, they're just NULL.

enisn commented 3 years ago

By the way, I got some feedbacks about including nulls in range query. There is a way to include nulls in your query:

Following class will solve this problem. But it's not a best practise so it'll not be inlcuded in AutoFilterer library by default. You can create in your project and use if you really need.

using System;
using System.Linq.Expressions;
using System.Reflection;
using AutoFilterer.Types;

namespace AutoFilterer.Types
{
        public class RangeOrNull<T> : Range<T> where T : struct, IComparable
        {
            public override Expression BuildExpression(Expression body, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
            {
                var rangeComparison = base.BuildExpression(body, targetProperty, filterProperty, value);

                var nullComparison = Expression.Equal(Expression.Property(body, targetProperty.Name), Expression.Constant(null));

                return  Expression.Or(rangeComparison, nullComparison);
            }
        }
}
- public Range<DateTime> PublishDate { get; set; }
+ public RangeOrNull<DateTime> PublishDate { get; set; }