为什么无法添加对象列表“ListOfMachines”即将出现空引用:
SFC.Terminal.dll中发生了'System.NullReferenceException'类型的异常,但未在用户代码中处理。
模型“MachineModel”:
public class MachineModel
{
public List<MachinesModelForList> ListOfMachines { get; set; }
public int QtyOfWorkerActivities { get; set; }
}
模型“MachinesModelForList”:
public class MachinesModelForList
{
public int ID;
public string Name { get; set; }
public string Description { get; set; }
public string UserName { get; set; }
public string OrderId { get; set; }
public string Index { get; set; }
public int Operation { get; set; }
public byte Shift { get; set; }
public int Status { get; set; }
public string StatusColor { get; set; }
public string StatusName { get; set; }
public int UserId { get; set; }
public int Slots { get; set; }
public DateTime? EndDate {get; set;}
public int MachineActivity { get; set;}
}
功能:
public MachineModel LoggedWorkerActivity()
{
var userloggeduserID = HttpContext.Current.User.Identity.GetUserId();
var DB = new TerminalDBContext();
var workerListOfMachinesID = DB.MachineActivity.Where(p => p.UserID.ToString() == userloggeduserID & p.EndDate == null).Select(p => p.MachineID).ToList();
var machineModel = new MachineModel();
foreach (int i in workerListOfMachinesID)
{
var ob = DB.Machine.Where(p => p.ID == i)
.Select(m => new MachinesModelForList
{
Status = DB.MachineActivity.Where(x => x.MachineID == m.ID).Select(p => p.StatusReason.Status.ID).FirstOrDefault(),
Description = m.Description,
Name = m.Name,
Slots = m.Slots,
ID = DB.MachineActivity.Where(x => x.MachineID == m.ID).Select(p => p.MachineID).FirstOrDefault(),
UserId = DB.MachineActivity.Where(x => x.MachineID == m.ID).Select(p => p.UserID).FirstOrDefault(),
EndDate = DB.MachineActivity.Where(x => x.MachineID == m.ID).Select(p => p.EndDate).FirstOrDefault(),
MachineActivity = DB.MachineActivity.Where(p => p.MachineID == m.ID & p.EndDate == null).Count()
}).FirstOrDefault();
machineModel.ListOfMachines.Add(ob);
machineModel.QtyOfWorkerActivities++;
}
return machineModel;
}
答案 0 :(得分:1)
只需创建列表实例
machineModel.ListOfMachines = new List<MachinesModelForList>();
machineModel.ListOfMachines.Add(ob);