2016-03-25 77 views
1

我有一個數據庫模型,看起來像這樣:選擇包括Repository模式返回null

  1. 投訴(T1)
  2. MonitoringComplaints(T2)
  3. 監測筆記(T3)

我的課堂每個看起來如下:

class Complaints{ 
//props 

    public virtual ICollection<MONITORING> MONITORINGs { get; set; } 
} 


class Monitoring{ 
//props 

    public virtual ICollection<MonitoringNotes> MONITORINGNotes { get; set; } 
} 

class MonitoringNotes{ 

//props 

} 

我讓我所有的數據,當我運行庫以獲取所有的波紋管

public IEnumerable<Complaints> GetAll() 
    { 

     try 
     { 
      return _context.Complaints 

       .Include(t => t.MONITORINGs) 
       .OrderBy(t => t.FileNum) 
       .ToList(); 
     } 
     catch (Exception ex) 
     { 
      _logger.LogError("Could not get complaint with checklist", ex); 
      return null; 
     } 
    } 

,但是當我添加註釋,監控與選擇,它將返回null:

public IEnumerable<Complaints> GetAll() 
    { 

     try 
     { 
      return _context.Complaints 

       .Include(t => t.MONITORINGs.Select(t3=>t3.MONITORINGNotes) 
       .OrderBy(t => t.FileNum) 
       .ToList(); 
     } 
     catch (Exception ex) 
     { 
      _logger.LogError("Could not get complaint with checklist", ex); 
      return null; 
     } 
    } 

此外,當我輸入select,我得到筆記的Intellisense,所以我不認爲它是我的實體。如果我正確使用select語句,有人能指出我正確的方向嗎?我在關於包含第三級關係的許多問題上使用了這個解決方案,例如:Entity Framework - Include Multiple Levels of Properties

+0

'Monitoring'是否已經有MonitoringNotes?因爲當沒有項目時,該屬性將爲空。只是檢查... – Chris

+0

@Chris謝謝你的檢查。它的確如此。一些投訴沒有任何監控數據,但投訴仍然顯示。包含select語句後,它只返回null。 – epv

+0

我跑你的代碼,它按預期工作。順便說一句'''在'.Include(.. Select()')行結尾處缺少一個''''。你是否有任何特殊的EF配置關係?我運行時沒有配置(按慣例) – Chris

回答

1

使用然後包括解決了我的問題。

public IEnumerable<Complaints> GetAll() 
{ 

    try 
    { 
     return _context.Complaints 

      .Include(t => t.MONITORINGs) 
        .ThenInclude(t3=>t3.MONITORINGNotes) 
      .OrderBy(t => t.FileNum) 
      .ToList(); 
    } 
    catch (Exception ex) 
    { 
     _logger.LogError("Could not get complaint with checklist", ex); 
     return null; 
    } 
}