c# - 插入 Entity Framework 后导航属性为 NULL

标签 c# .net entity-framework insert navigation-properties

我看到了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/

相关文章:

c# - 在单独的进程中从插件获取 WPF 应用程序中的 TextBox 焦点

.net - 作为项目经理,了解 .net 最重要的事情是什么?

c# - 如何使用 Entity Framework 将现有实体添加为新实体

c# - 如何为集合设计多重过滤器

c# - 用于重命名冲突默认值的 ProtoEnum 属性用法

c# - Unity GUIText 碰撞 C#

c# - 如何知道 CancellationToken 是否有注册的取消方法?

c# - NLog - 扩展 Nlog - callsite - dispose()

entity-framework - Entity Framework 中属性的延迟加载

c# - FluentValidation 和 Entity Framework 查找