Domanda

I have simple inteface:

public interface IValid
{
   DateTime From {get;set;}
   DateTime? To {get;set;}
}

I want to have possibility to write simple expression like that:

dbContext.SomeClass
   .WhereValidOnDate(DateTime.Today)
   .Where(x=> ...more_expressions...)
   .ToList();

I think, that I need write some class with method signature:

public static IQueryable<TSource> WhereValidOnDate<TSource>(this
    IQueryable<TSource> source)

Inside that method, I need to do some simple data comparisons (hardcoded), like:

x => x.From<= DateTime.Today && (x.To == null || x.To <= DateTime.Today

I tried expression tree - works, but syntax is a little more messy:

dbContext.SomeClass
   .Where(IsValidExpression)
   .Cast<SomeClass>()
   .Where(x=> ...more_expressions...)
   .ToList();
È stato utile?

Soluzione

Try this signature and implemenation:

public static IQueryable<T> WhereValidOnDate<T>(this IQueryable<T> source, DateTime other)
   where T : IValid
{
    return source.Where(x => x.From<= other && (x.To == null || x.To <= DateTime.Today));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top