2010-03-06 224 views
0

我使用LINQ to SQL和具有表像父子关系的LINQ to SQL

*ItemTable* 
ItemId Description 
1  Root 
2  Child 1 
3  Child 2 
4  Child of Child1 
5  Child of Child1 

*ItemChildTable* 
ParentID ChildId 
1   2 
1   3 
2   4 
3   5 

会是怎样使用LINQ to SQL 所以,我可以得到一个对象的关系就像

到他们的模型最好的方法
Item parent; 
Item child = parent.ChildItems.First(); 

在这里,我想childItems是同一类型的项目和父母与子女的关系存储在另一个表

+1

如果一个孩子不能有多个父母,那么您不应该使用链接表将孩子链接到父母,而是直接将外键直接放在父母的项目表中。 – BlueMonkMN 2010-03-07 14:12:19

+0

在我的情况下,孩子可以有多个父母,父母可以有多个孩子,因此桌子是这样设计的 – Ankit 2010-03-09 15:56:19

回答

0

你试图让递归在LINQ曲红霉素。我不知道它是否可能或者它是否有效。它认为你应该离开这个到C#。像这样:

var items = db.ItemTables.ToList(); 
var itemRelations = db.ItemChildTables.ToList(); 

var root = items.SingleOrDefault(item => ! itemRelations.Exists(rel => rel.ChildId == item.ItemId)); 
if(root != null) 
{ 
    Item rootItem = new Item(); 
    rootItem.ItemId = root.ItemId; 
    List<Item> childLessItems = new List<Item>{ rootItem }; 
    while(childLessItems.Count > 0) 
    { 
     List<Item> newChildLessItems = new List<Item>(); 
     foreach(var parent in childLessItems) 
     { 
      var childIds = from rel in itemRelations 
          where rel.ParentID == parent.ItemId 
          select rel.ChildId; 
      var children = items.Where(maybeChild => childIds.Contains(maybeChild.ItemId)); 
      foreach(var child in children) 
      { 
       Item childItem = new Item(); 
       childItem.ItemId = child.ItemId; 
       childItem.Parents.Add(parent); 
        parent.ChildItems.Add(childItem); 
       newChildLessItems.Add(child); 
      } 
     } 
     childLessItems = newChildLessItems; 
    } 
}