我目前在一个页面上工作,我可以列出帐户中的所有预订但遇到问题。我想访问分配到预订房间的所有房产,但我不太确定如何实现这一目标。
房型:
public class Room
{
public int RoomID { get; set; }
public int RoomNumber { get; set; }
public string RoomType { get; set; }
public string Image { get; set; }
public int Price { get; set; }
public int Adults { get; set; }
public int Childs { get; set; }
public bool SmokingRoom { get; set; }
public bool IsOccupied { get; set; }
public Floor Floor { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
预订模式:
public class Booking
{
public int BookingID { get; set; }
public Account Account { get; set; }
public DateTime DateOfReservation { get; set; }
public DateTime Arrival { get; set; }
public DateTime Departure { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public Room Room { get; set; }
public bool CheckIn { get; set; }
public bool CheckOut { get; set; }
public string Status { get; set; }
}
Databasehandler方法:
public static List<Booking> GetAllBookingsByAccount(int id)
{
HotelDbContext context = new HotelDbContext();
var bookings = context.Bookings.Where(b => b.Account.AccountID == id).ToList();
return bookings;
}
查看:
@if (Model.Bookings.Count != 0)
{
<table>
<thead>
<tr>
<th>Arrival</th>
<th>Departure</th>
<th>Hotel</th>
<th>Room</th>
<th>Persons</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@foreach (var booking in Model.Bookings)
{
<tr>
<td>@booking.Arrival.ToShortDateString()</td>
<td>@booking.Departure.ToShortDateString()</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>@booking.TotalPersons</td>
<td></td>
<td>@booking.Status</td>
</tr>
}
</tbody>
</table>
}
else
{
<p>You currently do not have any bookings.</p>
}
感谢您的时间!
答案 0 :(得分:2)
要使延迟加载工作,您需要将属性设置为虚拟,以便EF能够覆盖该属性。这意味着您不必调用Include方法。
将您的数据模型更新为:
public class Booking
{
public int BookingID { get; set; }
public virtual Account Account { get; set; }
public DateTime DateOfReservation { get; set; }
public DateTime Arrival { get; set; }
public DateTime Departure { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public virtual Room Room { get; set; }
public bool CheckIn { get; set; }
public bool CheckOut { get; set; }
public string Status { get; set; }
}
这将使EF能够延迟加载,并且您将能够访问该实体的所有属性,而无需任何额外的代码。
答案 1 :(得分:1)
您需要在预订时包含房间:
var bookings = context.Bookings.Include("Room").Where(b => b.Account.AccountID == id).ToList();