IQueryable<T> Question
Cur开发者_运维问答rently I return everything from my Repo as a List. I am looking to change these to IQueryable just so people can refine the results and not suffer from another sql request(I am using nhibernate).
I have a question though to make life easier on everyone I have something like this in my repo
public List<CalendarAppointment> GetAppointment(Student student, DateTime start, DateTime end)
{
List<CalendarAppointment> appointments = session.Query<CalendarAppointment>().Where(x => x.Student.Id == student.Id
&& x.Start.Date >= start.Date && x.End.Date <= end.Date)
.Take(QueryLimits.Appointments).ToList();
return appointments.ConvertToLocalTime(student);
}
public static List<CalendarAppointment> ConvertToUtcTime(this List<CalendarAppointment> appointments, Student student)
{
if (student != null)
{
TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(student.TimeZoneId);
foreach (var appointment in appointments)
{
appointment.Start = TimeZoneInfo.ConvertTimeToUtc(appointment.Start,info);
appointment.End = TimeZoneInfo.ConvertTimeToUtc(appointment.End,info);
}
}
return appointments;
}
So I get currently the results back and then convert the times into local time. This way we don't have to worry about it.
What happens if I do this with IQueryable. Will it go off and trigger the sql anyways?
Currently I return everything from my Repo as a List. I am looking to change these to IQueryable just so people can refine the results and not suffer from another sql request(I am using nhibernate).
There are few potential problems with what you have right now and how you want to fix it. Repository should not return all objects in the first place. It encapsulates data access and provides business-driven 'collection like' interface. Repository implementation belongs to data access layer that is smart enough to not return everything:
ordersRepo.FindDelinquent();
Returning IQueryable from public method is not the solution itself, it just shifts the problem somewhere else, somewhere where it does not belong. How would you test the code that consumes this repository? What is the point of generic repository, you might as well just use NHibernate directly and couple everything to it. Please take a look at these two articles and this answer:
- How To Write A Repository
- The
GenericRepository
Timezone conversion can be moved to the CalendarAppointment itself:
DateTime end = appointement.EndTimeInStudentTimeZone(Student t)
or in
List<CalendarAppointment> appts
= GetAppointmentInStudentTimeZone(
Student student, DateTime start, DateTime end)
Or better yet convert it before you actually need to use these times (in UI or Service).
精彩评论