在我的SQL Server数据库中,有两个表:RoomHotelHotelIDRoom表中的外键。在Room表中,有2个房间带有HotelID = 1

我的目标是尝试在HotelID方法中检索GET,然后结果应在Room表中显示酒店信息和HotelID信息,这些信息具有相同的Hotel

我从代码中得到的结果显示只有1个房间。它应该显示2个房间

{"item1":{"hotelID":1,"hotelName":"Dope Hotel","hotelAddress":"1234 Test St","hotelCity":"asdf","hotelState":"AB","hotelZip":"56452","hotelCountry":"USA","hotelPhone":"8081234567"},"item2":{"roomID":1,"roomName":"Ocean View","roomDescription":"This is room Description","hotelID":1}}


这是我的代码:

[HttpGet]
[Route("api/hotel/gethotel/{HotelID}")]
public IActionResult GetByHotelID(int HotelID, string[] roominfo)
{
        //check if the hotel ID is the same as the db hotelID
    var hotelinfo = _context.Hotels.FirstOrDefault(t => t.HotelID == HotelID);

    if (hotelinfo == null)
    {
        //if no item matches return id returning a http404 response
        return NotFound();
    }

    //return 200 with JSON response body, returning ObjectResult
    var rroominfo = _context.Rooms.FirstOrDefault(t => t.HotelID == HotelID);
    var hrinfo = (hotelinfo, rroominfo);

    if (rroominfo == null)
    {
        return new ObjectResult(hotelinfo);
    }
    else
    {
        return new ObjectResult(hrinfo);
    }
}


我的问题是如何为包含相同HotelID的结果获得多个房间?

最佳答案

我认为使用

var rroominfo = _context.Rooms.FirstOrDefault(t => t.HotelID == HotelID);


使您只能得到一个房间。它仅返回具有给定酒店ID的第一个房间。尝试使用

_context.Rooms.Where(t => t.HotelID == HotelID);


代替。

09-26 05:57