【问题标题】:Im trying to return related data in web api2 asp.net using DTO我正在尝试使用 DTO 在 web api2 asp.net 中返回相关数据
【发布时间】:2016-07-20 11:06:41
【问题描述】:
 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();
    }

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

【问题讨论】:

    标签: c# asp.net dto


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的建议。但它告诉我 HotelsDetailsDto 不包含与 LocationImage 相同的 LocationName 的定义
    • @Ransana 你读过答案的最后一部分吗?您是否在数据库中定义了 Hotel 和 Location 之间的关系?
    【解决方案2】:

    目前尚不清楚您使用的是哪个 EF 版本,但您似乎想要 eager load 您的 Hotels 对象。您可以通过阅读提供的文章或此 stackoverflow 答案 Entity framework linq query Include() multiple children entities

    来做到这一点

    它应该是这样的:

     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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多