在数据传输中包含相关实体 Object
Including related entities in a Data Transfer Object
我正在尝试提取会议列表及其相关预订。据我了解,我应该将我的数据放入 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; }
}
}
您可以使用 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是一个好的开始。
我正在尝试提取会议列表及其相关预订。据我了解,我应该将我的数据放入 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; }
}
}
您可以使用 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是一个好的开始。