markjprice / cs11dotnet7

Repository for the Packt Publishing book titled "C# 11 and .NET 7 - Modern Cross-Platform Development Fundamentals" by Mark J. Price
566 stars 206 forks source link

Refactoring the query cause an exception #81

Closed cmkaya closed 1 year ago

cmkaya commented 1 year ago

Chapter: 10

Page Number: 470 and 471

Section Title: Eager loading entities using the Include extension method

Step Number: 1

Problem to fix: Since it is stated that we should comment out the Include method but not modify the WriteLine(), it causes the System.NullReferenceException. In other words, the Count cannot reach the Products because of being null.

Screenshot 2023-08-17 at 17 47 34

Suggested solution: Either modify the WriteLine() removing the number of products or provide an explanation that the exception is occurring due to the Products being null.

markjprice commented 1 year ago

Products should not be null because you should have set Products to an empty HastSet<T> in the Category constructor, as shown on page 450: image

cmkaya commented 1 year ago

Hello Mark,

Thank you for your response. To be honest, I initially didn't include the Category() because I didn't fully grasp the concept. However, it's much clearer to me now.

I'd like to ask whether this approach is commonly employed in real-world applications. The reason I'm raising this question is because this is the first instance I've encountered this approach. Typically, I've found that navigation properties suffice for establishing relationships between entities.

markjprice commented 1 year ago

When you say "I initially didn't include the Category()", if you are referring to the following code:

public Category()
{
  Products = new HashSet<Product>();
}

Then that is a constructor and they are used all the time. The book covers constructors in Chapter 5. You might want to re-read it to remind yourself why they are used in almost all classes.

The code does use a navigation property to establish a relationship between entities. That is what Products is.

But if you do not use the Include extension method to load related data, then the Products navigation property would be null and would throw an exception when you try to read its Count, so you must set it to an empty collection when an instance of Category is instantiated, which is exactly what the code you didn't add does.

cmkaya commented 1 year ago

Thank you for taking the time to address my issue.