检索具有相同HotelID的数据

时间:2018-05-03 03:53:06

标签: c# visual-studio asp.net-core

在我的SQL Server数据库中,有两个表:<!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> $(document).ready(function(){ $('#f3_form').on('submit', function(e) { e.preventDefault(); var f3form = new FormData(this); console.log(f3form); $.ajax({ url: 'upload.php', type: 'POST', data: f3form, contentType: false, processData: false, success:function (data) { // body... } }) .done(function() { console.log("eeeeexito"+ data); }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); }); }); }); RoomHotelHotelID表中的外键。在Room表中,有2个房间Room

我的目标是尝试在HotelID = 1方法中检索HotelID,然后结果应显示酒店的信息以及GET的相同Room信息在HotelID表中。

我从我的代码中得到的只显示了一个房间。它应该显示2个房间

Hotel

这是我的代码:

{"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); } } 的结果的多个房间?

2 个答案:

答案 0 :(得分:3)

我认为使用

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

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

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

代替。

答案 1 :(得分:0)

我认为您可以使用Include()来加载酒店房间

var hotelinfo = _context.Hotels.Include(x => x.Rooms).FirstOrDefault(t => 
t.HotelID == HotelID);