我試圖讓用戶可以看到他們所做的預訂。我有一個模型,可以在不同的設施,大廳和房間中列出2種不同的預訂。因此,該模型包含大廳預訂和客房預訂列表。在我的控制器中,我試圖將所有大廳預訂添加到大廳預訂列表中,並且對於房間預訂也是如此。但我收到此錯誤c# - 對象引用未設置爲對象的實例 - LINQ
"Object reference not set to an instance of an object."
這裏是我的模型:
public class AllBookingsViewModel
{
public List<HallActivityBooking> HallBookingsList { get; set; }
public List<RoomBooking> RoomBookingsList { get; set; }
}
這裏是我的控制器:
public class BookingsController : BaseController
{
// GET: Bookings
public ActionResult Bookings()
{
//Get current user
var userId = User.Identity.GetUserId();
var currentUser = db.Users.Find(userId);
AllBookingsViewModel model = new AllBookingsViewModel();
//Fill activity booking
foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
{
model.HallBookingsList.Add(hallBooking); //<< This is where I get an exception
}
//Fill room bookings list
foreach (RoomBooking roomBooking in db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
{
model.RoomBookingsList.Add(roomBooking);
}
return View(model);
}
這裏是我試過(這些都不再仍然在我的代碼):
我試過宣佈這樣的模型:
var model = new AllBookingsViewModel
我試圖加入 「FirstOrDefault」 到LINQ聲明:
foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id).FirstOrDefault())
{
model.HallBookingsList.Add(hallBooking);
}
這給了我這個錯誤:
Severity Code Description Project File Line Suppression State Error CS0446 Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? ... 26 Active
幫助,將不勝感激
SOL VED
這裏是我做過什麼來解決這個問題:
的的for-each是沒有必要的,我只是需要給它的價值的LINQ的語句來初始化視圖模式:
AllBookingsViewModel model = new AllBookingsViewModel();
{
model.HallBookingsList = db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
model.RoomBookingsList = db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
};
每個HallBookings記錄是否都有一個與其關聯的CustomerUser?從你提到的錯誤信息,空引用異常,我可以假設至少有一個'HallBookings'作爲'CustomerUser'作爲空引用。 – Christos
FirstOrDefault僅返回一個匹配Where子句條件的對象。所以你不能使用foreach。哪一行代碼給出空引用錯誤? –
'AllBookingsViewModel'中的集合未初始化。 – kiziu