Reputation: 1681
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);
}
Upvotes: 0
Views: 1504
Reputation: 18181
When you do
var integerList = new IntegerList
{
Direction = integerViewModel.Direction
};
the associated Integers is not initialized, you can initialize it in IntegerList contsctructor. or do the following
var integerList = new IntegerList
{
Direction = integerViewModel.Direction,
Integers=new List<Integer>()
};
Upvotes: 0
Reputation: 218892
Because the Integers
property is not initialized and it is null. You were trying to call the Add
method on a null thing which gave you an error
Solution : Initialize the property in the IntegerList
class constructor
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 IntegerList()
{
Integers =new List<Integer>();
}
}
Upvotes: 4