views:

32

answers:

1

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)

A: 

You won't be able to use that in a query expression, but your second code snippet (calling Where explicitly) should be okay.

For the second query it's hard to say without seeing OtherFunctionThatCallsJoinByDateCheck - basically you won't be able to put it in a query expression, but if you can pass the query to this other function, that may work.

Jon Skeet
Ok, The Idea is that I have a lot of code that must call this condition, and It has to be used as a "standard"
Bogdan Maxim
@Bogdan: The problem is that query expressions automatically convert the code within them into lambda expressions, which for LINQ to SQL are then converted into expression trees. You don't *want* an expression tree containing a call to your helper method - you want the helper method itself to be called. That simply doesn't work in query expressions.
Jon Skeet