-2

In a sample MVC application that I am following from a book I have written this:

    public ViewResult List(string category, int page = 1)
    {

    private IProductsRepository repository;
    public int PageSize = 4;

    public ProductController()
    {

    }

    public ProductController(IProductsRepository productRepository)
    {
        this.repository = productRepository;
    }

        ProductsListViewModel viewModel = new ProductsListViewModel
        {
            Products = repository.Products
                .Where(p => category == null || p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
                .Take(PageSize),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = category == null ?
                    repository.Products.Count() :
                    repository.Products.Count(e => e.Category == category)
            },
            CurrentCategory = category
        };
        return View(viewModel);
    }

and

public class ProductsListViewModel
{
    public PagingInfo PagingInfo { get; set; }
    public IEnumerable<Product> Products { get; set; }

    public string CurrentCategory { get; set; }
}

When I want to run the application it crashes on the first method above saying Object reference not set to an instance of an object. but we are using new to create the object, so what is wrong?

  • 3
    Either `repository`, `repository.Products`, or one of the products in `repository.Products` is null. – Rotem Nov 17 '14 at 16:08
  • You can pretty much wrap whole program in one single LINQ statement... but it makes debugging hell lot of harder. Carefully read debugging suggestions in http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it - than split your code into multiple statements and debug each... It is not possible to help more than that without stepping through your code. – Alexei Levenkov Nov 17 '14 at 16:11
  • This is not a duplicate, there is something going on with Ninject. – ConfusedSleepyDeveloper Nov 17 '14 at 16:34

2 Answers2

1

Have you verified that the repository object or the Products object in the line referenced below is not null?

        Products = repository.Products
AperioOculus
  • 6,641
  • 4
  • 26
  • 37
1

Since the only two references you are dereferencing are repository and repository.Products either of them are null. Check in the debugger which and make sure you assign a value before trying to use the variable/reference

Rune FS
  • 21,497
  • 7
  • 62
  • 96
  • yes, you were right. repository was null. How to fix it? Is it because maybe something is missing in Ninject? I updated the code to show more about repository stuff. – ConfusedSleepyDeveloper Nov 17 '14 at 16:33