[英]Entity Framework Core Eager Loading Then Include on a collection
[英]Issue regarding Entity Framework Core eager loading an item inside of .Include
這是我的情況。 我有帖子和評論。 當我查詢以獲取帖子時,我是這樣寫的:
var queryable = _dataContext.Post
.Where(x => x.DateCreated <= initialDateOfPageLoad)
.AsQueryable();
var posts = await queryable
.Include(p => p.User)
.Include(c => c.Comments) // ***
.Include(l => l.Likes)
.OrderByDescending(p => p.DateCreated)
.ToListAsync();
現在評論實體有一個 Eagerly 加載的用戶。
public class Comment
{
public int Id { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
public Guid UserId { get; set; }
public User User { get; set; } // ***
public string Body { get; set; }
public bool Modified { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
每當我收回我的帖子時,我都會將評論映射到這樣的 dto 中:
public class CommentDto
{
public int Id { get; set; }
public string Body { get; set; }
public DateTime DateCreated { get; set; }
public Guid UserId { get; set; }
public int PostId { get; set; }
public string DisplayName { get; set; } // ***
public string ImagePath { get; set; } // ***
}
所以我需要應該急切地加載注釋的用戶來插入用戶實體上可用的用戶 ID 和圖像路徑。
現在奇怪的是,評論的用戶只有在該用戶發表帖子時才會急切地加載......
如果我嘗試對尚未發表帖子的用戶發表評論,我將獲得空值,並且在調試時它會顯示該用戶未加載。 但是,一旦該用戶發表了帖子(與用戶評論的帖子無關),那么所有內容都會急切地與評論一起正確加載。
有人可以解釋一下這里發生了什么嗎? 我不希望每個用戶都發帖,但我希望他們發表評論。 為什么在這種情況下急切加載不起作用?
您不會急切地加載用戶的評論,但是如果他們發表了帖子,那么它會自動為您修復。
將.Include(p => p.Comments).ThenInclude(c => c.User)
到您的查詢中以修復它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.