Can anybody suggest the cause of the following problem? My code is breaking on the line
integerList.Integers.Add(integer); with the error message
Object reference not set to an instance of an object. IntegerList.Integers is null which I suspect is the cause but what is the solution? Do I have to set IntegerList.Integers values when I initialize the variable so it is never null?
Models
public class IntegerList { public int IntegerListID { get; set; } public string Direction { get; set; } public long Performance { get; set; } public virtual ICollection<Integer> Integers { get; set; } } public class Integer { public int IntegerID { get; set; } public int IntegerValue { get; set; } public int IntegerListID { get; set; } public virtual IntegerList IntegerList { get; set; } } ViewModel
public class IntegerViewModel { [UIHint("Integers")] public IntegerValueViewModel IntegerValues { get; set; } public string Direction { get; set; } } public class IntegerValueViewModel { public ICollection<int> IntegerValue { get; set; } } Controller
[HttpPost] public ActionResult Index(IntegerViewModel integerViewModel) { if (ModelState.IsValid) { var integerList = new IntegerList { Direction = integerViewModel.Direction }; foreach (var item in integerViewModel.IntegerValues.IntegerValue) { var integer = new Integer { IntegerValue = item }; integerList.Integers.Add(integer); }
NullReferenceExceptionare the same. Please see "What is a NullReferenceException in .NET?" for some hints.