开发者

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

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, e开发者_开发知识库1.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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜