Accepted answer

In this case there is no reason to get a List in memory and then do the projection, you can do this directly from EF instead. Even if there is no relationship defined EF will return null for CategoryName if you project the the results. If you go to memory first then an NRE is expected if there is no Category relationship.

public List<DocumentViewModel> All()
    return _context.Document.Select(x => new DocumentViewModel
        { DocumentId = x.DocumentId,
          DocumentPath = x.DocumentPath,
          CategoryId = x.CategoryId,
          CategoryName = x.Category.CategoryName}).ToList();

Original reason why it is failing.

  1. There is at least one entity that does not have a corresponding relationship with Category.
  2. You do not have lazy loading enabled (which is a good thing) and if that is the case you should use Include to return the relationship.

Related Articles