I saw this post that suggests an answer but my situation is a bit different.
// Create a new Lunch entity with these two properties.
Lunch lunchEntity = new LunchEntity();
lunchEntity.UserId = userId;
lunchEntity.MealId = mealId;
// Add the entity to the DbContext and save the changes.
restaurantEntities.Lunches.Add(lunchEntity);
restaurantEntities.SaveChanges();
// Get the Lunch entity that we inserted above.
Lunch mySavedLunchEntity = restaurantEntities.Lunches.Find(lunchEntity.Id);
Now, after inserting the Lunch entity, I need to have its instance with all of its navigation properties included. That's why I use the Find() method to select the newly created entity. The problem is that the User navigation property is null, while the Meal navigation property has a reference to the correct object.
Moreover, if I execute this statement
Lunch mySavedLunchEntity = restaurantEntities.Lunches.Find(lunchId);
separately in another method that is supposed to retrieve a Lunch entity for a particular Id, all navigation properties are included correctly.
So, my question is why all my navigation properties are included when I just query a given element, and some of them are not, if I query the element only after it has been inserted?
You could try:
Lunch mySavedLunchEntity = restaurantEntities.Lunches.Where(l => l.LunchId == lunchId).Include(l => l.User).Include(l => l.Meal)
This forces EF to load the two navigation properties instead of Lazy loading them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.