I have an instance of the following:
Expression>
I wish to convert it to an instance of the following
Fortunately, for what you want it is not necessary to play with expression trees. What you do need is to enhance the template restriction:
public static IQueryable FilterByDate(this IQueryable src, DateTime startDate, DateTime endDate) where TModel: class, IRequiredDate {
return src.Where(x => x.Date >= startDate && x.Date <= endDate);
}
A bit of explanation. Using LINQPad you can see that the expression trees generated are different when the class
requirement is removed. The Where
clause is like this when the restriction is present:
.Where (x => (x => x.Date >= startDate && x.Date <= endDate))
Whereas when the restriction is removed the expression changes as follows:
.Where (x => (x => (((IRequiredDate)x).Date >= startDate) && (((IRequiredDate)x).Date <= endDate)))
The expression tree has some extra casts, which is why in this form Entity Framework tells you it cannot work with instances of type IRequiredDate
.