簡體   English   中英

在實體框架中插入后,導航屬性為NULL

[英]Navigation property is NULL after insert in Entity Framework

我看到這篇文章提出了答案,但我的情況有所不同。

// 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()方法選擇新創建的實體的原因。 問題是用戶導航屬性為null,而餐導航屬性具有對正確對象的引用。

而且,如果我執行此語句

Lunch mySavedLunchEntity = restaurantEntities.Lunches.Find(lunchId);

在應該為特定ID檢索Lunch實體的另一種方法中,所有導航屬性均正確包含在內。

因此,我的問題是,如果僅在插入元素后才查詢該元素,為什么只在查詢給定元素時包括所有導航屬性,而有些不包括?

您可以嘗試:

Lunch mySavedLunchEntity = restaurantEntities.Lunches.Where(l => l.LunchId == lunchId).Include(l => l.User).Include(l => l.Meal)

這迫使EF加載兩個導航屬性,而不是延遲加載它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM