Search code examples
c#entity-frameworkfluent

Entity Framework Fluid Query Start and End Dates When Start is Nullable


I have a model with following properties (Start is nullable while End is required):

public DateTime? Start { get; set; }
public DateTime End { get; set; }

I query the active events as follows:

var result = _db.ActiveEvents
                .Where(x => x.Start <= today && x.End >= today)
                .ToList();

This doesn't give me my desired result. I want the result to be within the Start and End when both Start and End have values.

However, when Start is null, it must be ignored and only query for End.


Solution

  • Try this

    var result = _db.ActiveEvents
                    .Where(x => (x.Start == null or x.Start <= today) && x.End >= today)
                    .ToList();
    

    Both conditions must be true for a record to be included: The event has either started or has no start date, and The event has not ended yet.