2011-03-02 81 views
0

我正在將linq2sql轉換爲實體框架。實體框架4急切加載根本不工作!

在轉換過程中,我需要將包含eagar加載的linq2sql的加載轉換爲轉換,但是加載不成功。當我使用分析器時,我發現子實體被加載並被訪問。

DataBaseEntities context = new V3C_DataBaseEntities(); 

context.Agents.Include("Account"); 

Agent ag = context.Agents.Where(x => x.Login_ID == "2").SingleOrDefault(); 

// here the account should have been loaded, 
// but actually they are loaded with the line below this is executed. 

Console.WriteLine(ag.Account.ID.ToString()); 

如果做以下工作,它完美的工作,但我必須按照問題中提到的方式。

var c = (from ag in context.Agents.Include("Account") 
        where ag.Login_ID == "2" 
        select ag).SingleOrDefault(); 

我還想加載子實體類型安全的方式。

回答

0

這是您的查詢不執行急於負載:

context.Agents.Include("Account"); 

Agent ag = context.Agents.Where(x => x.Login_ID == "2").SingleOrDefault(); 

如果更改查詢放置Include我相信你會得到你想要的結果表達式中。

Agent ag = context.Agents 
        .Include("Account") 
        .Where(x => x.Login_ID == "2").SingleOrDefault(); 

在我的測試,我已經看了導致生成的SQL,第一個表達式不相關的表連接。您的Include被忽略,因爲它不是查詢表達式的一部分。

+0

嗨,正如我所說這一個工作正常,但我必須做另一種方式,因爲我有一個非常大的方法,並根據參數加載該方法的datacontext。底線是,我必須加載問題中定義的datacontext。 – 2011-03-02 23:13:07

+0

其次,請注意,我想以最順利的方式將linq2sql轉換爲實體框架。 – 2011-03-02 23:39:08

4

你不能這樣做,因爲你寫的問題。您必須在查詢中使用包含。從Linq2Sql轉換到EF時沒有平滑的方式。您必須接受新的API並正確使用它。如果你想輸入的安全包括版本,則必須下載Entity Framework Feature CTP5或寫你的own extension

var query = context.Agents.Include("Account"); 
Agent ag = query.Where(x => x.Login_ID == "2").SingleOrDefault(); 

只能使用此。