2016-12-01 90 views
0

我有懶加載關閉,並且代理創建並不重要(嘗試均爲 true和false,沒有區別)。明確包含的實體框架導航屬性爲空

我有這樣的模式:

public class Comment{ 

    [Required] 
    public int SenderID { get; set; } 

    public User Sender { get; set; } 

} 

(當然,我有一個用戶類)。

在數據庫級別,我確認發件人是有效的用戶對象。我有一些IQueryable<Comment>命名commentsQuery(即基本上採用從後一些評論然後我包括髮件人導航屬性並執行查詢:

var comments = commentsQuery.Take(50).OrderBy(c => c.ID).Include(c => c.Sender).ToList();

然而,一些名單內評論的對象必須即使我已明確包含導航屬性,它們的Sender設置爲null。

如果我打開延遲加載,它可以正常工作,但我不想打開延遲加載

爲什麼顯式包含的必需導航屬性爲null? (我在實體框架6.1.3)

回答

0

好吧,只是想出了自己。當我從數據庫上下文構建它時,必須將發件人包含在原始查詢中。

我所用:

var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).FirstOrDefaultAsync(); 
IQueryable<Comment> commentsQuery = post.Comments.ActiveObjects().OrderByDescending(c => c.ID).AsQueryable(); 

然後,我認爲實體框架只是忽略(我認爲這是微軟的側面設計問題)後,包括導航屬性(commentsQuery.[...].Include(c => c.Sender))。

我已經修改了原來的查詢,包括二級導航屬性:

var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).Include(p => p.Comments.Select(c => c.Sender)).FirstOrDefaultAsync(); 

(注意添加.Include(p => p.Comments.Select(c => c.Sender)

現在,我的查詢工作正常。我不確定這是否是最好的方法,但不管這個問題的範圍如何。