2011-11-07 116 views
1

我有一個關於實體框架的多對多關係的問題。多對多的關係,EDMX,實體框架,SQL Express數據庫

好的,所以我有一個現有的SQL Express數據庫,我已經擴展到包括一個名爲「國家」的新表。因爲我想在「國家」和另一個表「語言」之間有多對多的關係,所以我製作了一張交叉表。到現在爲止還挺好。

我有一個VS項目和我已經從新的數據庫更新的EDMX文件。圖表看起來不錯,我可以看到國家和語言之間的多對多關係。我無法看到國家和語言之間的交集表(但根據Google,這是一項功能)。

我已經手動填寫了SQL Server Management Studio中的國家和交叉表。

正如我已經理解實體框架中的多對多關係,我應該能夠通過編寫country.Language簡單地獲取與一個國家相關的語言。下面是具體的代碼:

string code = "fi"; 

     using (var context = new FooEntities()) 
     { 
      IQueryable<Country> countriesTest = context.Country; 
      IQueryable<Country> countries = context.Country.Where(s => s.CountryCode == code); 
      Country country = countries.First(); //this works, I get the correct Country 
      EntityCollection<Language> languages = country.Language; //this does not work, collection is empty 

沒有語言返回。我有雙重檢查,我在路口表中鍵入正確的價值觀,我失去的東西嗎?

回答

1

是否啓用LazyLoading? (打開EDMX文件,並在屬性窗口設置「延遲加載啓用」真

或者用XML編輯器編輯EDMX

<edmx:ConceptualModels> 
    <Schema Namespace="FooModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"> 
     <EntityContainer Name="FooEntities" annotation:LazyLoadingEnabled="true"> 

或者編程啓用它。

using (var context = new FooEntities()) 
{ 
    context.ContextOptions.LazyLoadingEnabled = true; 
    IQueryable<Country> countriesTest = context.Country; 

或渴望加載語言:

context.Country.Include("Language") 
+0

好問題。我沒有看到延遲加載啓用在我的屬性窗口中,我有A連接類別和模式類別。我應該把context.ContextOptions.LazyLoadingEnabled = true;在Designer.cs文件中 - 如果是的話,在哪裏? – sreddy

+0

除了模式和連接類別之外,我還有代碼生成和數據庫腳本生成。查看更新的答案 – Fabiano