繁体   English   中英

亲子关系Linq与SQL

[英]Parent Child Relationship 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与Items的类型相同,并将父子关系存储在另一个表中

您试图在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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM