2017-06-01 124 views
0

我第一次使用實體框架。我寫了下面的簡單查詢:使用實體框架返回所有相關實體

public List<Request> GetResult(string code) 
{ 
    List<Request> requests = new List<Request>(); 

    using (var db = new Context()) 
    { 
     requests = (from c in db.Requests where c.Code == code select c).ToList(); 
    } 

    return requests; 
} 

有幾個相關實體的Request對象,如具有與Request表1對1的關係Results表。但是他們全都回來了。

我該如何查詢實體框架並返回一個實體及其所有相關實體?

TIA

+0

您使用的是什麼版本的實體框架?你可以發佈你的'Request'對象嗎? – Steve

+0

https://stackoverflow.com/questions/14512285/entity-framework-is-there-a-way-to-automatically-eager-load-child-entities-wit – spender

回答

2
使用預先加載集

單查詢

db.Requests.Where(req => req.Code == code) 
    .Include(req => req.Results) // Joining is performed here 
    .Include(req => req.SomeOtherProperty) 
    .ToList() 
使用

// Hits the database once. 
var requests = db.Requests.Where(req => req.Code == code).ToList(); 
var requestIDs = requests.Select(req => req.ID); 
// Hits the database another time to load your Results property. 
db.Results.Where(res => requestIDs.Contains(res.RequestID)).Load(); 

如果延遲加載啓用了明確的裝載個

多個查詢,每次你訪問Request列表Results屬性,查詢被執行到數據庫加載它適合你,這可能導致在N上+1問題。儘管惰性加載在EntityFramework Core上尚不可用。

+0

添加System.Data.Entity命名空間後,您的加載示例很好地完成了這個技巧。謝謝! – Nugs

0

如果你要選擇的對象被加載使用

db.Entry(Requests).Reference(p => p.Code).Load(); 

如果你想在你的DataContext構造函數自動加載所有

this.Configuration.LazyLoadingEnabled = true; 
+0

'LazyLoadingEnabled'爲請求發出一個新的查詢一個卸載的虛擬財產。根據OP的要求,它不會自動加載這些屬性。 – spender