我在使用具有多对多关系的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' 。 “”
答案 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查询的投影部分设置为仅从必要的列中获取数据。这应该减少数据库和你的应用程序之间飞行的数据量。