我试图用相关的预订来列出会议清单。据我了解,我应该将我的数据放入DTO。我能够得到一份会议清单......
var meetings = from m in db.meetings.Take(2)
select new MeetingDTO()
{
meetingid = m.meetingid,
meetingname = m.meeting_name,
businessname = m.business.name
};
return meetings;
我尝试了几种不同的方法来包含相关的预订数据,但无法确定语法。
我知道这已经过时了,但这就是我想要做的事情......
var meetings = from m in db.meetings.Take(2)
select new MeetingDTO()
{
meetingid = m.meetingid,
meetingname = m.meeting_name,
businessname = m.business.name,
bookingsDTOs = from b in db.bookings
select new bookingsDTO()
{
bookingid = b.bookingid,
bookingname = b.name
};
};
return meetings;
这是我的DTO结构......
namespace testapi.Models
{
public class MeetingDTO
{
public int meetingid { get; set; }
public string meetingname { get; set; }
public string businessname { get; set; }
public virtual ICollection<bookingsDTO> bookingsDTOs { get; set; }
}
public class bookingsDTO
{
public int bookingid { get; set; }
public string bookingname { get; set; }
}
}
答案 0 :(得分:3)
您可以使用Include
扩展方法将相关实体显式加载为查询的一部分:
var meetings = from m in db.meetings.Include(m=>m.bookings).Take(2)
select new MeetingDTO()
{
meetingid = m.meetingid,
meetingname = m.meeting_name,
businessname = m.business.name
bookingsDTOs = m.bookings.Select(b=>new bookingsDTO()
{
bookingid = b.bookingid,
bookingname = b.name
})
};
return meetings;
为了让您的生活更轻松,我建议您先了解Automapper。配置映射后,您可以执行以下操作:
var meetings = from m in db.meetings.Include(m=>m.bookings).Take(2).ProjectTo<MeetingDTO>();
这个tutorial是一个好的开始。