简体   繁体   中英

Null reference exception on navigation property

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);
            }

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>();
    }
}

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>()

                };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM