Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7071977
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:45:09+00:00 2026-05-28T05:45:09+00:00

First up: we are not doing TPH (table per hierarchy), that would make this

  • 0

First up: we are not doing TPH (table per hierarchy), that would make this a lot simpler.

I have about 20 POCOs that all have similar properties in some cases. The similar properties I care about are ___.CreatedDate and ___.UpdatedDate. For some of the POCOs, UpdatedDate doesn’t make sense, so they don’t have that property. CreatedDate will always exist, UpdatedDate may be null. Sometimes there’s a third field as well.

The query to retrieve objects from the database always looks the same, regardless of which of the 20 POCOs I’m querying. However, the query was duplicated 20 times, one for each type of the object. I was able to break out the retrieve part to an extension method (off of IDbSet<T>) to do the initial lookup and joins, leaving the date range filtering as an exercise to the consumer. I’m now wanting to consolidate 20 nearly-identical looking date range filters into one, but running into problems with query comprehension.

The date filtering logic, per POCO, is that UpdatedDate should be checked and its value compared to a threshold. If UpdatedDate was null (or the property didn’t exist), then CreatedDate should be used instead.

</background>

I started by creating a static property getter on each POCO, which I named “DateFields”. It’s typed as an IEnumerable<Expression<Func<T, DateTime?>>> that looks like this:

get
{
    yield return x => x.UpdatedDate;
    yield return x => x.CreatedDate;
    yield return x => x.Date;
}

These fields are returned in the order I want them checked, and are unique to each POCO.

I then created a predicate to check each value against a high and low range:

public static bool DatesBetween<T> (T value, IEnumerable<Expression<Func<T, DateTime?>>> dates, DateTime? dateFrom, DateTime? dateTo)
{
    var firstDate = dates
        .Select(expression => expression.Compile())
        .FirstOrDefault(func => func(value) != null);

    if (firstDate == null)
        return false;

    var minDate = dateFrom.GetValueOrDefault(SqlDateTime.MinValue.Value);
    var maxDate = dateTo.GetValueOrDefault(SqlDateTime.MaxValue.Value);

    var actualDate = firstDate(value);

    return (minDate <= actualDate && actualDate <= maxDate);
}

However, as expected, when I try and use this in my IQueryable, I get a runtime exception, because there’s no translation to DatesBetween in SQL. I was hoping that by keeping the expression tree, I could … I dunno … keep EF happy. The whole thing is used like this:

return Entities
    .GetEntitiesBySomeField(field := "magic value")
    .Where(entity => RepositoryExtensions.DatesBetween(entity, MyPOCO.MyDates, dateFrom, dateTo));

Is what I’m asking clear, and is there a way to accomplish this kind of generic filtering without doing an AsEnumerable () (which does work, but doesn’t accomplish my goal of filtering on the DB).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:45:10+00:00Added an answer on May 28, 2026 at 5:45 am

    I’ve done something similiar to this in a project recently. What I ended up doing was implementing the repository pattern and created a method on the repository called “ApplyFilter” which looked something like:

    void ApplyFilter(Expression<Func<TEntity, bool>> predicate)
    {
        if(this.resultSet == null)
        {
            this.resultSet = this.context.Set<TEntity>().AsQueryable();
        }
    
        this.resultSet = this.resultSet.Where(predicate);
    }
    

    And had a property on my repository called “ResultSet” which just returned the IQueryable<TEntity> resultSet field and forced an enumeration of the results (triggering EF’s database call). This way I could apply all the dynamically created expressions in a clean why before enumerating the results.

    The real difference between what my code does and what yours is doing is my code appends the boolean predicate to the final Expression tree where as you are trying to use yours within the final expression tree. My way basically creates/appends a WHERE clause to the SQL, yours tries to generate a SQL function call from the “DatesBetween” method.

    Here is something to try:

        public static Expression<Func<TEntity, bool>> MakeDateRange<TEntity>(DateTime? dateFrom, DateTime? dateTo)
        {
            var et = typeof(TEntity);
            var param = Expression.Parameter(et, "a");
            var prop = et.GetProperty("UpdatedDate");
            Expression body = null, left = null, right = null;
            if (prop == null)
            {
                prop = et.GetProperty("CreatedDate");
                if (prop == null)
                {
                    prop = et.GetProperty("Date");
                }
            }
    
            if (dateFrom.HasValue)
            {
                left = Expression.GreaterThanOrEqual(Expression.PropertyOrField(param, prop.Name), Expression.Constant(dateFrom.GetValueOrDefault()));
            }
    
            if (dateTo.HasValue)
            {
                right = Expression.LessThanOrEqual(Expression.PropertyOrField(param, prop.Name), Expression.Constant(dateTo.GetValueOrDefault()));
            }
    
            if (left != null && right != null)
            {
                body = Expression.AndAlso(left, right);
            }
            else if (left != null)
            {
                body = left;
            }
            else
            {
                body = right;
            }
    
            return Expression.Lambda<Func<TEntity, bool>>(body, param);
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a stored procedure that returns two int Values. The first can not
A few quick searches discovered that I'm obviously not the first person to have
i'm trying to make this form sticky but it's not doing. What i'm trying
I have found that the first time a UITableView loads, it does not respond
My first question here, hopefully I'm not doing it wrong. My problem is that
This should be really simple, I have found that the first argument is the
I have a problem with selecting not first selector using attributeContains jQuery('div[id*=abc]:not(:first)').hide();
First of all: I am not an experienced ClearCase user, but I have lots
I'm not doing anything fancy with habtm. What i'm trying to do is have
First of all, I'm a beginner on shell-script. This code I've done is not

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.