I'm trying to implement Query objects into my code, but have encountered a problem. When passing meetId = 1
to GetMeetingDTO an exception is thrown by SingleOrDefault()
. My Database currently holds 6 meetings all with unique Ids (1-6). I have checked if values are passed correctly via FilterOptions
to FilterMeetingsBy
and I looks ok (using Visual Studio). Apparrently no filtering is applied thus SingleOrDefault
throws the error. I have tested leaving out the extension method and applying .Where(p => p.Id == 1)
directly on the context. Then no error is thrown...
public async Task<MeetingDTO> GetMeetingDTO(long meetId)
{
IEnumerable<Meeting> meetings = await context.MeetDbSet
.FilterMeetingsBy(new FilterOptions { MeetingId = meetId }).ToListAsync();
return mapper.Map<MeetingDTO>(meetings.SingleOrDefault());
}
Here is the extension method
public static class FilterMeetings
{
public static IQueryable<Meeting> FilterMeetingsBy(this IQueryable<Meeting> meetings, FilterOptions options)
{
if (options == null)
return meetings;
if (options.MeetingId.HasValue)
{
meetings.Where(p => p.Id == options.MeetingId.Value);
return meetings;
}
if (options.SortFromDate.HasValue)
meetings.Where(p => p.StartDate >= options.SortFromDate.Value);
if (options.SortToDate.HasValue)
meetings.Where(p => p.StartDate <= options.SortToDate.Value);
return meetings;
}
}
public class FilterOptions
{
public long? MeetingId { get; set; }
public DateTime? SortFromDate { get; set; }
public DateTime? SortToDate { get; set; }
}
question from:
https://stackoverflow.com/questions/65887386/extension-method-not-applying-linq-where-clause 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…