How to modify type parameter of Expression>?

前端 未结 3 1264
青春惊慌失措
青春惊慌失措 2021-01-04 22:59

I have an instance of the following:

Expression>

I wish to convert it to an instance of the following

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 23:30

    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.

提交回复
热议问题