2

I have two tables Category and Document. See relationships in picture See picture

I wrote the following query to select data from both tables based on relationship

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

        }

when this function is called , I get the following error

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Here are my modals

document

public class Document
    {
        [Key]
        public int DocumentId { get; set; }
        [Required]
        public string DocumentPath { get; set; }
        public Nullable<int> CategoryId { get; set; }
        public virtual Category Category { get; set; }
    }

Category

public class Category
    {

        [Key]
        public int CategoryId { get; set; }
        [Required]
        public string CategoryName { get; set; }
        public virtual ICollection<Document> Documents { get; set; }
    }

DocumentViewModel

 public class DocumentViewModel
    {
        public int DocumentId { get; set; }
        public string DocumentPath { get; set; }
        public int? CategoryId { get; set; }
        public string CategoryName { get; set; }
    }

Any Idea where am doing mistake?

1
  • That means your data integrity is flawed. Check in your data which documents are orphaned (has no corresponding category). Commented Jul 19, 2018 at 17:17

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.