我正在尝试使用DTO返回webapi2asp.net中的相关数据

本文关键字:net webapi2asp 数据 返回 DTO | 更新日期: 2023-09-27 17:57:45

 public class hotelapiController : ApiController
{
    private POSDBEntities db = new POSDBEntities();

    public IList<HotelsDetailsDto> GetHotels()
    {
        return db.Hotels.Select(p => new HotelsDetailsDto
        {
            Id = p.Id,
            Name = p.Name,
            Address = p.Address,
            Description = p.Description,
            Offering = p.Offering,
            Gps = p.Gps,
            NumberOfRooms = p.NumberOfRooms,
            Commission = p.Commission,
            Rating = p.Rating,    
            HotelTypeName=p.HotelTypeName,
            HimageId = p.HimageId,          //HimageId is a foreign key
            AveragePrice=p.AveragePrice,
            BookingEmail =p.BookingEmail,
            LocationId =p.LocationId,      //LocationId is a foreign key               
          }).ToList();
    }

当poster返回JSON数据时,它只返回外键的id。但我需要它在位置表中返回数据,即位置的名称和图像,而不仅仅是位置Id。我使用数据传输对象和数据库优先方法,而不是代码优先。我该怎么做?

我正在尝试使用DTO返回webapi2asp.net中的相关数据

如果您在数据库中正确定义了外键,那么(根据我的经验(当您要求实体框架从数据库创建模型时,它应该已经识别出了这一点,并为您提供了模型中的链接实体。例如,您的"酒店"应具有"位置"属性。所以你应该已经能够写这样的东西:

public IList<HotelsDetailsDto> GetHotels()
{
    return db.Hotels.Select(p => new HotelsDetailsDto
    {
        Id = p.Id,
        //removed other lines for brevity
        LocationName = p.Location.Name,
        LocationImage = p.Location.Image
  }).ToList();
}

如果不是这样,请正确定义表之间的数据库外键,然后更新实体框架模型。然后,它应该为您提供访问所需实体的权限。

目前尚不清楚您使用的EF版本,但似乎您想急切地加载Hotels对象。您可以通过阅读提供的文章或这个stackerflow答案来实现这一点实体框架linq query Include((多个子实体

它应该是这样的:

 public IList<HotelsDetailsDto> GetHotels()
        {
            return db.Hotels.Include(x => x.Himage).Include(x => x.Location)
.Select(p => new HotelsDetailsDto
            {
                Id = p.Id,
                Name = p.Name,
                // Other fields
                HimageId = p.Himage.Id,          //HimageId is a foreign key
                LocationId =p.Location.Id,      //LocationId is a foreign key               
              }).ToList();