0

I need help with the function below, it was working fine for a few months until now. Now I get:

System.NullReferenceException: 'Object reference not set to an instance of an object.' x was null.

I'm not sure why now is giving me NullReference, orders list is not empty - it has 41 items. Any help is appreciated!

public dynamic UserMostBoughtItem(int userId)
{
    try
    {
        var carts = _cartRepository.GetAllUserCarts(userId);
        if(carts.Count > 0)
        {
            List<Order> orders = new List<Order>();

            for (var i = 0; i < carts.Count; i++)
            {
                var single = _orderRepository.GetOrderItemsOneByOneByCartId(carts[i].Id);
                orders.Add(single);
            }

            // !EXCEPTION! 
            var fav = orders
                .GroupBy(x => x.ItemTitle, x => x.Quantity)
                .Select(x => new { ItemTitle = x.Key, Quantity = x.Sum() })
                .OrderByDescending(x => x.Quantity)
                .Take(1)
                .SingleOrDefault();

            var image = _orderRepository.FindOrderItemByItemTitle(fav.ItemTitle);

            // Find Favorite Item
            var favorite = _favoriteRepository.FindByUserId(userId);
            if (favorite == null)
            {
                var newFav = new Favorite()
                {
                    UserId = userId,
                    Item = fav.ItemTitle,
                    Quantity = fav.Quantity,
                    Image = image.ItemImage,
                };
                _favoriteRepository.Create(newFav);
            }
            else
            {
                favorite.Item = fav.ItemTitle;
                favorite.Quantity = fav.Quantity;
                favorite.Image = image.ItemImage;
                _favoriteRepository.Update(favorite);
            }

            return fav;
        }
        else
        {
            return null;
        }
    }
    catch (FavoriteModelException ex)
    {
        LogMessage(RecordType.Error, ex.Message);
        return null;
    }
}

I'm trying to find the favorite menu item for a user.

screenshot

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
William
  • 35
  • 5
  • 3
    you see element at index 40? It **is** null. – MakePeaceGreatAgain Jan 27 '22 at 15:57
  • Presumably `GetOrderItemsOneByOneByCartId` can return null. You need to account for that when building up `orders`. – Jon Skeet Jan 27 '22 at 15:58
  • in the for loop change the condition to for (var i = 0; i < carts.Count -1 ; i++) – Amjad S. Jan 27 '22 at 16:01
  • 1
    I was trying to check if the ordering system was ok. Apparently, there was a bug that allowed me to create empty order. I deleted the empty order and now is ok. Problem solved – William Jan 27 '22 at 16:01
  • Btw., why add the items to a list? You could apply the LINQ query directly to the result of `GetOrderItemsOneByOneByCartId`. Also, you could start with `.Where(x => x is not null)`. – Olivier Jacot-Descombes Jan 27 '22 at 16:10
  • Welcome to StackOverflow @William! Congratulations on your first question. I highly recommend you spend some time reading the Help sections. In particular: https://stackoverflow.com/help/how-to-ask – Scott Solmer Jan 27 '22 at 16:10

1 Answers1

0

It looks like item 40 is null. A null exception is thrown when you try to call a method or get a property from an item that is null. That Linq is going through each item on that list and pulling properties from it. Possibly try having a foreach that goes through the list and deals with nulls first.

 foreach (var item in orders)
        {
            if (item == null)
            {
                //do something
            }
        }
PWCoder
  • 93
  • 6