实体框架查询#1

时间:2009-10-29 16:13:42

标签: c# entity-framework entity

我正在试图弄清楚如何限制我的子数据集只包含活动记录...

    // 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));

显然这些都不起作用。我不知道怎么做...

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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 :(得分: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);

“故事”中的每个故事应该只有活动的任务。