检索多对多关系数据

时间:2014-02-23 08:04:17

标签: c# entity-framework-4

我在使用具有多对多关系的Entity Framework时遇到了一些问题:

我有一个Reservation类,其中Membership为多对多关系:

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

如何从我从预订中选择的foreip循环的memberip表单中检索MembershipID

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????
    });
}

如果我回复reservations我得到了:

  

'ObjectContent`1'类型无法序列化内容类型'application / json的响应主体;字符集= UTF-8' 。 “”

1 个答案:

答案 0 :(得分:0)

您的模型说:有一系列会员资格连接到该预订,看起来您正试图只获取其中一个。你确定这是你需要的吗?

您可以获取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()
    });
}

我已为您的查询添加了Include来电,急切地加载Membership内容。否则,由于延迟加载,你会在foreach循环中得到很多不必要的数据库调用。

您还应该将EF查询的投影部分设置为仅从必要的列中获取数据。这应该减少数据库和你的应用程序之间飞行的数据量。