score:2

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 Query

More Query from same tag