這是解釋爲here (EF 4.1 code-first: How to load related data (parent-child-grandchild)?)的問題的第二步。 按@Slauma的指導我可以檢索數據。我的第一個代碼是這樣的:EF 4.1代碼優先:如何在使用包含和/或選擇方法時訂購導航屬性?
var model = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order) // ordering parent
.ToList();
foreach (var child in model) { // loading children
DbContext.Entry(child)
.Collection(t => t.Children)
.Query()
.OrderBy(t => t.Order) // ordering children
.Load();
foreach (var grand in child.Children) { // loading grandchildren
DbContext.Entry(grand)
.Collection(t => t.Children)
.Query()
.OrderBy(t => t.Order) // ordering grandchildren
.Load();
}
}
它的工作原理,但是,這將發出許多查詢針對數據庫和我正在尋找一種方式來做到這一切在短短的一個查詢。通過@Slauma的指導意見(上面的鏈接解釋)我更改查詢到這一個:選擇時,他們
var model2 = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order)
.Include(p => p.Children // Children: how to order theme???
.Select(c => c.Children) // Grandchildren: how to order them???
).ToList();
現在,我怎麼可以爲了孩子(和孫子)(如第一碼以上)?
看看這個問題:http://stackoverflow.com/questions/4156949/ef4-linq-ordering-parent-and-all-child-collections-with-eager-loading-include。你所要做的就是「急切加載」,顯然,你不能在'Include'中使用'OrderBy'。 – devuxer
是的,我知道急切的加載,如果你看第一個代碼(由我自己創建),你會看到我在每個級別的每個對象上使用一個foreach語句(頂級爲子級,子級爲孫級)正如你準備好的鏈接所解釋的那樣。但是這需要對數據庫進行更多的查詢!我正在尋找一種方法在一個查詢中完成所有操作,而不是更多! –
您是否可以急於加載整個結構,然後在需要時在視圖中進行排序?在你的數據訪問邏輯中,你應該泄露表示邏輯(排序)幾乎沒有理由。 –