修复NULL异常

时间:2014-11-17 16:06:27

标签: 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(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);
    }

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

    public string CurrentCategory { get; set; }
}

当我想运行应用程序时,它崩溃了上面的第一个方法Object reference not set to an instance of an object.,但我们正在使用new创建对象,那么出了什么问题?

2 个答案:

答案 0 :(得分:1)

您是否确认下面引用的行中的存储库对象或产品对象不为空?

        Products = repository.Products

答案 1 :(得分:1)

由于您解除引用的唯一两个引用是存储库和存储库。它们中的任何一个都是null。检查调试器,确保在尝试使用变量/ reference

之前指定一个值