我试图让用户可以看到他们所做的预订。我有一个模型,可以在不同的设施,大厅和房间中列出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