Question

I have some problem using Entity Framework with a many-to-many relationship:

I have a Reservation class with Membership as a many-to-many relationship:

public class Reservation
{
    public virtual ICollection<Membership> Membership { get; set; } 
}

How can I retrieve MembershipID from membersip form foreach loop that I selected from reservation:

reservations = reservationRepo.Reservations.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,
        MembershipID = reservation.Membership????
    });
}

If I just return reservations I got :

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top