FadoBagi
FadoBagi

Reputation: 181

How to create and add object to collection of a class

I have two entities - Movie and Review. I want to create a new review for a specific movie. Then add that review in the collection in the Movie entity. When I debug the code below, I can read the movie variable and see that it does indeed have this new review in its collections. But when I get the same movie again, the review collection is empty.

Movie

enter image description here

Review

enter image description here

Creating and adding the review

var movie = data.Movies.Find(5);

var newReview = new Review
{
   Content = "Example",
   MovieId = 5
};

movie.Reviews.Add(newReview);
data.Reviews.Add(newReview);
data.SaveChanges();

Upvotes: 2

Views: 289

Answers (1)

Avogadro
Avogadro

Reputation: 363

The problem is fetching the data again.

Based on your comment, you find the movie again using

data.Movies.Find(5)

However, this will not automatically bring the related data back with the movie. EF Core requires by default to eagerly load those related entities using .Include()

To remedy the data fetching for your query it would look like this:

data.Movies
   .Include(m => m.Reviews)
   .FirstOrDefault(5)

If a movie could have zero reviews and you want to perform a true LEFT JOIN, then modify the above to:

data.Movies
   .Include(m => m.Reviews).DefaultIfEmpty()
   .FirstOrDefault(5)

Upvotes: 1

Related Questions