我正在尝试学习LINQ,我有一个null ref异常错误的问题,我无法理解。
我的项目/意图概述:我在数据库中有2个表。一个是客户,一个是订单。Customers表有ID、Name列。Orders表有orderID、Description和CustomerID列。
Customers
ID Name
1 eeee
2 dddd
3 ffff
Orders
ID Description CustomerID
1 sdffds 2
2 dsfasdf 2
3 fjdsa 1
4 dfsa 3
我要做的是选择并只显示有超过1个订单的客户(在本例中,只有ID为2的客户)。
我有一个ViewModel类
public class ViewModel
{
public List<Customer> Customers { get; set; } //list of customer objects
public List<Order> Orders { get; set; } //list of customer objects
}
在home控制器的index动作中,我有:
public ActionResult Index()
{
Context db = new Context(); //create new Context Object named db which contains lists of objects pulled from database server
ViewModel model = new ViewModel(); //create new ViewModel Object named model which contains lists of objects
model.Customers = db.Customers.ToList(); //pull Customers data table from db
var groups = db.Orders.GroupBy(custgroup => custgroup.CustomerId).Where(group => group.Count()>1); //pull Orders data table from db and group by CustomerID, and choose only groups with more than 1 records.
foreach (var group in groups)
{
foreach (Order order in group)
//foreach (var order in group)
{
model.Orders.Add(order); //***The null exception occurs here where 'Orders' is null. Check for null before calling method***
}
}
return View(model);
}
实际上,我要做的是将订单按客户分组,并选择我所选择的订单组。然后将组中的单个记录放回原始对象格式。从调试来看,我认为我已经实现了过滤的过程。当我试图将记录放回模型时,问题就出现了。订单的列表。
null异常发生在内部foreach中,其中'Orders'列表为空。错误指示是. orders列表为空和/或未声明。但是我认为这个列表是在顶部的声明ViewModel model = new ViewModel();
中声明的。
如何修复这个空异常错误?TIA。
您忘记初始化model.Orders.
把
model.Orders = new List<Order>();
创建模型后,它应该可以工作