无法正确汇编查询

时间:2013-08-15 19:03:15

标签: c# linq entity-framework

3表:

  1. ParentTable:ParentID (假设有一个ParentID = 5)
  2. ParentChildrenTable:ParentID,ChildrenID (假设有3个ParentID = 5的关系行)
  3. ChildrenTable:ChildrenID,ChildrenName (假设有3个ParentID = 5的子项,例如:A,B,C)
  4. 我试图做一些类似“让所有ChildID = 5的孩子并打印他们的名字”的事情 使用Entity Framework和LinQ

    使用伪这就是我的意思:

    Parent fifthParent = db.ParentTable.FirstOrDefault(p => p.ParentID == 5);
    
    foreach (ParentChildren parentChildren in fifthParent.ParentChildren) // will iterate 3 times
    {
        //get each child seperatly according
        foreach(Child child in parentChildren.Children)
        {
            //print A (on 1st iteration)
            //print B (on 2nd iteration)
            //print C (on 3rd iteration)
        }   
    }
    

    据我所知,它应该是2个for-loops,尽管我在过去的2个小时里一直在努力奋斗。 希望你能提供代码样本,因为我仍然无法掌握这些查询的原理。

4 个答案:

答案 0 :(得分:2)

您可以使用SelectMany展平内部集合:

Parent fifthParent = db.ParentTable.FirstOrDefault(p => p.ParentID == 5);

var children = fifthParent.ParentChildren.SelectMany(c=>c.Children)

foreach (Child parentChildren in children)
{
   //print children.
}

答案 1 :(得分:1)

我会从另一个方向开始:

foreach ( var child in db.ChildrenTable
    .Where( c => c.ParentChildren.Any( pc => pc.ParentID == 5 ) ) )
{
    var foo = child.Name // or whatever else
}

答案 2 :(得分:1)

您的ParentChildrenTable课程应该看起来像这样

public class ParentChildrenTable
{
  public int Id { get; set; }
  public int ParentId { get; set;}
  public int ChildId {get; set; }

  public virtual ParentTable Parent { get; set; }
  public virtual ChildrenTable Child { get; set; }
}

这意味着您可以在第一个循环中访问Child对象的ParentChildrenTable属性:

foreach (ParentChildren parentChildren in fifthParent.ParentChildren) // will iterate 3 times
{
    ChildrenTable child = parentChildren.Child;

    //print A (on 1st iteration)
    //print B (on 2nd iteration)
    //print C (on 3rd iteration)
}

更新

要使用单个LINQ查询执行此操作,您可以使用SelectMany然后调用Select

var children = db.ParentTable.Where(p => p.ParentID == 5)
                             .SelectMany(p => p.Children)
                             .Select(pc => pc.Child);

或者你可以从孩子开始:

var children = db.ChildrenTable.Where(c => c.ParentChildren.Any(pc => pc.ParentId == 5));

答案 3 :(得分:1)

这会将所有内容连接在一起,并将其过滤为仅返回其父ID为5的子项。

var childrenOfFifthParent = 
    from parent in context.ParentTable

    join parentChild in context.ParentChildrenTable on parent.ParentID
        equals parentChild.ParentID

    join child in context.ChildrenTable on parentChild.ChildID
        equals child.ChildID

    where parent.ParentID == 5
    select child;

然后你可以做类似的事情:

foreach (var child in childrenOfFifthParent.ToList())
{
    // print the child
}