0

["ProductCategories" field is null](https://i.stack.imgur.com/wVpDD.png)

Product Categories field is null. I suspect is causing Error: Object reference not set to the instance of an object" Source of suspicion:from Stack Overflow particularly " Better still is to not have a null in your collection in the first place."

But database says this field is populated. my DB Also, if I keep stepping through the page above in debug mode it will render the page successfully. But I obviously don't want it to stop me each time the page calls this(ie."myProducts") data model which is a Paginated List of type "Product".

This razor page should render each field of a paginated list of type "Product" that is called. My question is why is my Product Category foreign key field showing null when it is populated in the database

Oop. Fixed. I didn't include

.Include(pc => pc.ProductCategories)

in my IQueryable call to context, as shown below:

IQueryable<Product> ProductIQ = from p in Context.Product
                                        .Include(pc => pc.ProductCategory)
                                        select p;



        if (!String.IsNullOrEmpty(searchString))
        {
            ProductIQ = ProductIQ.Where(p => p.ProductName.Contains(searchString));
        }

        switch (sortOrder)
        {
            case "name_desc":
                ProductIQ = ProductIQ.OrderByDescending(p => p.ProductName)
                    .ThenByDescending(p => p.Wholesaler).ThenByDescending(p => p.ProductDescr1);
                break;
            default:
                ProductIQ = ProductIQ.OrderBy(p => p.ProductName)
                    .ThenByDescending(p => p.Wholesaler).ThenByDescending(p => p.ProductDescr1);
                break;
        }


        var pageSize = Configuration.GetValue("PageSize", 10);


        myProducts = await PaginatedList<Product>.CreateAsync(
            ProductIQ.AsNoTracking(), pageIndex ?? 1, pageSize);

        return Page();

Works fine now.

0 Answers0