我看到了this post这暗示了一个答案,但我的情况有点不同。
// 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);
现在,在插入 Lunch 实体后,我需要包含其所有导航属性的实例。这就是为什么我使用 Find() 方法来选择新创建的实体。问题在于 User 导航属性为 null,而 Meal 导航属性引用了正确的对象。
此外,如果我执行这条语句
Lunch mySavedLunchEntity = restaurantEntities.Lunches.Find(lunchId);
在另一个应该为特定 Id 检索 Lunch 实体的方法中,所有导航属性都被正确包含。</p>
所以,我的问题是,为什么当我只查询给定元素时我的所有导航属性都包含在内,而如果我仅在插入元素后查询元素,其中一些属性却不包含?
最佳答案
你可以试试:
Lunch mySavedLunchEntity = restaurantEntities.Lunches.Where(l => l.LunchId == lunchId).Include(l => l.User).Include(l => l.Meal)
这会强制 EF 加载这两个导航属性,而不是延迟加载它们。
关于c# - 插入 Entity Framework 后导航属性为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28085526/