0

I am having trouble with this. I am trying to add a viewmodel oject to an ICollection of viewmodel objects...

It gives a Null Reference Exception. Here is the inner exception.

  System.NullReferenceException occurred
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=<Cannot evaluate the exception source>

Its saying it cannot evaluate the exception source....

I have a viewmodel:

    public class ClientJobListingViewModel
{
    public int Id { get; set; }
    public string JobType { get; set; }
    public string Status { get; set; }
    public string WarrantyStatus { get; set; }
    public string NumberOfVisits { get; set; }
}

that is added to an entity as a collection of viewmodels:

public class ClientDetailsViewModel
{
    ...
    public ICollection<ClientJobListingViewModel> Jobs { get; set; }
}

I am using a foreach loop to create the viewmodel and then add it to the collection... simple.

if (_client.Jobs.Count() > 0)
{
     foreach (Job job in _client.Jobs)
     {
          var _job = new ClientJobListingViewModel();

          _job.JobType = "test1";
          _job.Status = "test2";
          _job.WarrantyStatus = "test3";
          _job.NumberOfVisits = "4";

          _model.Jobs.Add(_job);
          }
     }
....

Yet when I run this I am getting a null reference exception error..

Showing that the view model is not null.

It looks like I have coded this correctly but maybe I have missed something.. Visual Studio certainly thinks so..

What am I doing wrong?

si2030
  • 3,895
  • 8
  • 38
  • 87
  • `_model.Jobs` property must be initialized before doing `_model.Jobs.Add(_job)`. – ekad Feb 23 '17 at 07:26
  • `ICollection` is an interface. You need initialize a `List` first and add the item to it and assign that list to the `Jobs` property (and `ICollection` does not even have an `Add` method). But why not just make the property `List` in the first place? –  Feb 23 '17 at 07:26

1 Answers1

3

You have to initialize Jobs property in ClientDetailsViewModelconstructor or before use of _model.Jobs.Add(_job);

 public class ClientDetailsViewModel
{
    public ClientDetailsViewModel()
    {
        Jobs = new List<ClientJobListingViewModel>();
    }
    public ICollection<ClientJobListingViewModel> Jobs { get; set; }
}
Jignesh Variya
  • 1,869
  • 16
  • 12