2012-12-08 50 views
2

假設我有以下的「富」與「酒吧」實體:實體框架可以通過相關實體的屬性對實體進行排序嗎?

class Foo { 
    int FooId; 
    string FooName; 
} 

class Bar { 
    int BarId; 
    Foo RelatedFoo; 
    string BarName; 
} 

同樣假設,我想「RelatedFoo」偷懶加載默認。

在實體框架中,是否有可能做一個查詢,返回一個「Bar」實體的枚舉,其中元素按「bar.RelatedFoo.FooName」排序?

如果是這樣,這可以在固定數量的數據庫查詢中完成嗎?我想避免做N+1 queries

如果沒有,這是可能在另一個.NET ORM框架?

回答

1
var bars = _context.Bars.OrderBy(b => b.RealtedFoo.FooName) 

你也可以只帶回那些酒吧是RealtedFoo不爲空

var bars = _context.Bars.Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName) 

更新:

//For EF only 
    _context.Configuration.LazyLoadingEnabled = false 

    //If you want to bring back RealtedFoo then include it. 
//Otherwise, you can just query for it and not use the Include() extension. 
    var bars = _context.Bars.Include(b => b.RealtedFoo).Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName) 
+0

這將在一個單一的數據庫查詢做些什麼呢? – chrisdfrey

+0

我不確定實際查詢在SQL Server中的外觀如何,但是您可以運行SQL Profiler來查看。你在問什麼? – DDiVita

+0

我想確保我不會通過訪問RelatedFoo來執行N個查詢。 – chrisdfrey