2009-10-29 174 views
2

我試圖找出如何限制我的孩子的數據集只包括主動記錄...實體框架查詢#1

// Here's what I have currently... 
    m_BackLoggerEntities.Stories 
    .Include("Sprints") 
    .Include("Tasks") 
    .Include("Efforts") 
    .Include("Products") 
    .First(s => s.StoryId == id); 


    // Here's what I thought I could do... 
    m_BackLoggerEntities.Stories 
    .Include("Sprints") 
    .Include("Tasks") 
    .Include("Efforts") 
    .Include("Products") 
    .Where(s => s.Tasks.Active) 
    .First(s => s.StoryId == id); 


    // I also tried this... 
    m_BackLoggerEntities.Stories 
    .Include("Sprints") 
    .Include("Tasks") 
    .Include("Efforts") 
    .Include("Products") 
    .First(s => s.StoryId == id && s => s.Tasks.Active)); 

顯然都未工作。我不知道怎麼回事做到這一點...

+2

到底是什麼問題?你是否遇到異常?零結果?結果太多? ??? – jrista 2009-10-29 16:22:17

回答

1

看一看Alex James Tip 37。 據例如在鏈接的文章,這是可以做到這樣的:

var query = from story in m_BackLoggerEntities.Stories 
      where story.StoryId == id 
      select new { 
          story, 
          Tasks = from task in story.Tasks 
            where task.Active 
            select task 
         }; 

var stories = query 
    .AsEnumerable() 
    .Select(x => x.Story); 

每個故事裏面的「故事」的應該只有活動的任務。

1

我發現「模擬」我要的是要使用的唯一途徑...

 var storyToDetail = 
      m_BackLoggerEntities.Stories 
       .Include("Sprints") 
       .Include("Tasks") 
      .Include("Efforts") 
      .Include("Products") 
       .First(s => s.StoryId == id); 

然後在在foreach查看...

  <% foreach (var task in Model.Tasks.Where(t => t.Active)) 

但是,這當然帶來了更多的記錄,然後我想。

2

你需要的東西是這樣的:

Model = m_BackLoggerEntities.Stories 
    .Include("Sprints") 
    .Include("Tasks") 
    .Include("Efforts") 
    .Include("Products") 
    .SingleOrDefault(s => s.StoryId == id); 

然後,在你的看法:

@foreach (var task in Model.Tasks.Where(t => t.Active)) 
+0

這是一個非常古老的問題....「2009年10月29日」謝謝,但我試圖避免使用foreach。它如何實施對我來說是無足輕重的。 – Altonymous 2013-05-22 21:46:41