0

I have the following VM, Model and Method(in a controller lets say). When the Add() is called, the IDE throws the 'object not set to an instance' error. The properties in the Model are assigned values correctly but for some reason the Add() bombs...Any suggestions?

View Model:

public class RevenueByViewModel
{       
    public ICollection<RevByModality> RevByModalities { get; set; }
}

Model:

public class RevByModality
{
    public string DeliveryType { get; set; }
    public decimal? ActualPrice { get; set; }
}

Method:

public RevenueByViewModel GetRevByModality(string bu, string region, string fiscalYearQuarter, string deliveryType)
    {


        RevByModality revByPublic = new RevByModality();
        decimal? publicRev = 0.0m;

        //...additional objects removed for brevity

        var revByModality = (from r in db.Registrations
                             where (bu == "All" || r.BusinessUnit.Equals(bu)) &&
                                     (region == "All" || r.Region.Equals(region)) &&
                                     (r.FiscalYearQuarter == fiscalYearQuarter) &&
                                     (deliveryType == "All" || r.DeliveryType.Equals(deliveryType))
                             select new 
                             {
                                 r.DeliveryType,
                                 r.ActualPrice
                             }).ToList();


            foreach(var item in revByModality)
            {
                if (item.DeliveryType.Equals("Public"))
                {
                    publicRev += item.ActualPrice;
                }
                //...additional logic removed for brevity
            }

        RevenueByViewModel vm = new RevenueByViewModel();

        revByPublic.DeliveryType = "Public";
        revByPublic.ActualPrice = publicRev;
        vm.RevByModalities.Add(revByPublic);


        return vm;

    }
JReam
  • 898
  • 2
  • 13
  • 28

1 Answers1

1

Because, in your viewmodel you're not generating a collection for the .Add to be added to

You can either add this in the flow, or add it to the viewmodel directly:

 RevenueByViewModel vm = new RevenueByViewModel();
 vm.RevByModalities = new List<RevByModality>();

or

public class RevenueByViewModel
{        
    public RevenueByViewModel()
    {
        RevByModalities = new List<RevByModality>();
    }

    public ICollection<RevByModality> RevByModalities { get; set; }
}
freedomn-m
  • 27,664
  • 8
  • 35
  • 57