Closed cmkaya closed 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:
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.
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.
Thank you for taking the time to address my issue.
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 theWriteLine()
, it causes theSystem.NullReferenceException
. In other words, theCount
cannot reach theProducts
because of beingnull
.Suggested solution: Either modify the
WriteLine()
removing the number of products or provide an explanation that the exception is occurring due to theProducts
beingnull
.