Your model says: there is a collection of Memberships connected to that Reservation and looks like you're trying to get just one of them. Are you sure that's what you need?
You can get list of MembershipID
:
reservations = reservationRepo.Reservations.Include("Membership").Where(r =>
r.StartDatetime >= requestDate && r.EndDatetime <= endDate
&& r.Branch.BranchID == branchId).AsEnumerable();
foreach (var reservation in reservations)
{
reservationList.Add(new ReservationModel
{
ReservationID = reservation.ReservationID,
StartDatetime = reservation.StartDatetime,
EndDatetime = reservation.EndDatetime,
MembershipIDs = reservation.Membership.Select(m => m.MembershipID).ToList()
});
}
I've added Include
call to your query, to eagerly load Membership
content. Otherwise you'd get a lot of unnecessary DB calls within foreach
loop because of lazy loading.
You should also probably make the projection part of your EF query, to fetch data from necessary columns only. That should decrease number of data flying between database and you application.