Jamex
Jamex

Reputation: 1222

LINQ c# mvc4 null reference exception

I am trying to learn LINQ and I am having a problem with a null ref exception error that I can't understand.

Overview of my project/intent: I have 2 tables in the DB. One is Customers and one is Orders. The Customers table has the ID, Name columns. The Orders table has orderID, Description and CustomerID column.

Customers
ID       Name
1        eeee
2        dddd
3        ffff

Orders
ID       Description   CustomerID
1        sdffds        2
2        dsfasdf       2
3        fjdsa         1
4        dfsa          3

What I am trying to do is to select and display only the customers that have more then 1 orders (in this case, only customer with ID 2).

I have a ViewModel class

 public class ViewModel
    {
      public List<Customer> Customers { get; set; } //list of customer objects 
      public List<Order> Orders { get; set; } //list of customer objects 
    }

In my homecontroller's index action, I have:

        public ActionResult Index()
        {

         Context db = new Context(); //create new Context Object named db which contains lists of objects pulled from database server

         ViewModel model = new ViewModel(); //create new ViewModel Object named model which contains lists of objects

         model.Customers = db.Customers.ToList(); //pull Customers data table from db 

         var groups = db.Orders.GroupBy(custgroup => custgroup.CustomerId).Where(group => group.Count()>1); //pull Orders data table from db and group by CustomerID, and choose only groups with more than 1 records.

            foreach (var group in groups)
            {
                foreach (Order order in group)
                //foreach (var order in group)
                {
                    model.Orders.Add(order); //***The null exception occurs here where 'Orders' is null. Check for null before calling method***
                }
            }


            return View(model);
           }

In effect, what I am trying to do is to group orders by customers and select the groups of orders of my choosing. Then put back the individual records from the groups into the original object format. From the debug, I think I have achieved the filtering process. The problem occurs when I try to put the records back into the 'model.Orders' list.

The null exception occurs inside the inner foreach where 'Orders' list is null. The error indication is that the .Orders list is null and/or has not been declared. But I am thinking that the list was declared in the statement ViewModel model = new ViewModel(); at the top.

How do I fix this null exception error? TIA.

Upvotes: 0

Views: 361

Answers (1)

Taugenichts
Taugenichts

Reputation: 1365

You forgot to initialize model.Orders.

Put

model.Orders = new List<Order>();

after you create the model and it should work.

Upvotes: 4

Related Questions