C# 修复空异常

C# 修复空异常,c#,asp.net-mvc,asp.net-mvc-5,C#,Asp.net Mvc,Asp.net Mvc 5,在我从一本书中获得的MVC应用程序示例中,我写了以下内容: public ViewResult List(string category, int page = 1) { private IProductsRepository repository; public int PageSize = 4; public ProductController() { } public ProductController(IProduc

在我从一本书中获得的MVC应用程序示例中,我写了以下内容:

    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);
    }

公共类ProductsListViewModel
{
公共分页信息分页信息{get;set;}
公共IEnumerable乘积{get;set;}
公共字符串CurrentCategory{get;set;}
}

当我想要运行应用程序时,它会在上面的第一个方法上崩溃,即
对象引用未设置为对象的实例。
但是我们正在使用
新建
来创建对象,那么有什么不对呢

您是否已验证以下引用行中的存储库对象或产品对象不为空

        Products = repository.Products

因为您要取消引用的仅有两个引用是repository和repository。它们中的任何一个都是空的。检查调试器,确保在尝试使用变量/引用之前分配了一个值,
repository
repository.Products
,或
repository.Products
中的一个产品。Products为空。您几乎可以在一个LINQ语句中包装整个程序。。。但这让调试变得更加困难。仔细阅读中的调试建议,然后将代码拆分为多个语句并调试每个语句。。。如果不仔细检查代码,就不可能提供更多帮助。这不是重复的,Ninject有问题。是的,你是对的。存储库为空。如何修复它?是不是因为Ninject中缺少了什么?我更新了代码以显示更多关于存储库的内容。
        Products = repository.Products