Linq generic Expression in query on "element" or on IQueryable (multiple use)

Posted by Bogdan Maxim on Stack Overflow See other posts from Stack Overflow or by Bogdan Maxim
Published on 2010-05-12T14:08:40Z Indexed on 2010/05/12 14:24 UTC
Read the original article Hit count: 252

Filed under:
|
|
|

Hi, I have the following expression

public static Expression<Func<T, bool>> JoinByDateCheck<T>(T entity, DateTime dateToCheck) where T : IDateInterval
{
    return (entityToJoin) => 
        entityToJoin.FromDate.Date <= dateToCheck.Date && (entityToJoin.ToDate == null || entityToJoin.ToDate.Value.Date >= dateToCheck.Date);
}

IDateInterval interface is defined like this:

interface IDateInterval 
{
    DateTime FromDate {get;}
    DateTime? ToDate {get;}
}

and i need to apply it in a few ways:

(1) Query on Linq2Sql Table:

var q1 = from e in intervalTable where FunctionThatCallsJoinByDateCheck(e, constantDateTime) select e;

or something like this:

intervalTable.Where(FunctionThatCallsJoinByDateCheck(e, constantDateTime))

(2) I need to use it in some table joins (as linq2sql doesn't provide comparative join):

var q2 = from e1 in t1 join e2 in t2 on e1.FK == e2.PK where OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate)

or

var q2 = from e1 in t1 from e2 in t2 where e1.FK == e2.PK && OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate)

(3) I need to use it in some queries like this:

var q3 = from e in intervalTable.FilterFunctionThatCallsJoinByDateCheck(constantDate);

Dynamic linq is not something that I can use, so I have to stick to plain linq.

Thank you

Clarification:

Initially I had just the last method (FilterFunctionThatCallsJoinByDateCheck(this IQueryable<IDateInterval> entities, DateTime dateConstant) ) that contained the code from the expression.

The problem is that I get a SQL Translate exception if I write the code in a method and call it like that.

All I want is to extend the use of this function to the where clause (see the second query in point 2)

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about LINQ