2012-04-12 55 views
0

我有兩個元素Sfera和Contenuti之間的N-N關係。如何處理實體框架.NET 3.5中的N-N關係

在特別基金項目我看到Contenuti實體集,並在Contenuti我看到了特別基金集..

當我通過代碼添加一個新的項目,我使用的結構,如:

using (IndexDB DB = new IndexDB()) 
     { 
      try 
      { 
       var newContenuto = new Contenuto(); 
       newContenuto.Cancellato = false; 
       newContenuto.PK_Content_ID = tt_content_id; 
       newContenuto.URL = URL; 
       foreach(long sphere in SphereID) 
       { 
        try 
        { 
         var sfere = from sfera in DB.Sfera where sfera.PK_Sfera == sphere select sfera; 
         newContenuto.Sfera.Add(sfere.First()); 
         sfere.First().Contenuto.Add(newContenuto); 
        } 
        catch (Exception exc) 
        { 
         return new StandardResponse() {Success = false, Message = exc.Message}; 
        } 
       } 
       DB.AddToContenuto(newContenuto); 
       DB.SaveChanges(); 
       return new StandardResponse() {Success = true}; 
      } 
      catch (Exception e) 
      { 
       return new StandardResponse() { Success = false, Message = e.Message + e.StackTrace }; 
      } 

如果我看看我的數據庫,它會很好地存儲我在右邊的「NN」表中的兩個元素之間的關係....但是當我嘗試訪問元素Contenuto.Sfera和Sfera.Contenuto總是空集。 。

要訪問我做類似的事情:

using (IndexDB DB = new IndexDB()) 
     { 
      var sfere = from sfera in DB.Sfera where sfera.PK_Sfera == IDSfera && sfera.Attiva select sfera; 

      if (!sfere.Any()) 
      { 
       response.Add(new UrlResponse() { Success = false, ErrorMessage = "" }); 
      } 
      var sferaSelezionata = sfere.First(); 
//HERE sferaSelezionata.Contenuto.Count == 0 even if on DB there are MANY "connections" 
} 

}

我如何處理呢?

非常感謝!

+0

你確定sferra.Attiva永遠是真的,或者對於至少一條記錄是真的嗎?另外,您確定IDSfera的值是否等於至少一條記錄中的PK_Sfera的值?而且這兩個條件在至少一個記錄中都是正確的? – 2012-04-12 15:17:38

+0

是的,我敢肯定...你可以在代碼中看到,如果sfere爲空(所以沒有與Attiva == true匹配的結果,ID等於我的參數),會引發異常並且其他代碼無法訪問! – 2012-04-12 15:22:21

+0

我看不到引發異常的代碼。我們正在查看相同的代碼嗎? – 2012-04-12 15:32:42

回答

1

在您的查詢中嘗試使用Include()

var sfere = from sfera in DB.Sfera.Include("Contenuto") where sfera.PK_Sfera == IDSfera && sfera.Attiva select sfera;