在LINQ中创建层次结构

时间:2013-10-14 19:25:33

标签: c# linq

我有一个数据库表,表示具有多级层次结构的帐户。每行都有一个“AccountKey”代表当前帐户,可能还有一个“ParentKey”代表父母的“AccountKey”。

我的模型类是“AccountInfo”,其中包含有关帐户本身的一些信息以及子帐户列表。

将此平面数据库结构转换为层次结构的最简单方法是什么?可以直接在LINQ中完成,还是我需要在事后循环并手动构建它?

模型

public class AccountInfo
{
    public int AccountKey { get; set; }
    public int? ParentKey { get; set; }
    public string AccountName { get; set; }

    public List<AccountInfo> Children { get; set; } 
}

LINQ

var accounts =
    from a in context.Accounts
    select new AccountInfo
        {
            AccountKey = a.AccountKey,
            AccountName = a.AccountName,
            ParentKey = a.ParentKey                            
        };

2 个答案:

答案 0 :(得分:1)

您只需为父键创建关联属性:

public class AccountInfo {
    ... // stuff you already have
    public virtual AccountInfo Parent { get; set; }
}

// in the configuration (this is using Code-first configuration)
conf.HasOptional(a => a.Parent).WithMany(p => p.Children).HasForeignKey(a => a.ParentKey);

使用此设置,如果您希望延迟加载子项,则可以通过延迟加载在查询中或查询之外遍历层次结构,确保将属性设置为虚拟。

要为给定父级选择所有子级,您可以运行以下查询:

var children = context.Accounts
    .Where(a => a.AccountKey = someKey)
    .SelectMany(a => a.Children)
    .ToArray();

答案 1 :(得分:1)

您当前拥有的结构实际上是一个层次结构(邻接列表模型)。问题是,你想保留这种分层模型吗?如果你这样做,那就是一个名为MVCTreeView的Nuget包。这个包直接与你描述的表结构一起工作 - 在它中,你可以为你的UI创建一个树视图,在每个级别实现CRUD操作,等等。我必须这样做,我写了一篇关于CodeProject的文章,展示了如何cascade通过C#删除SQL中的邻接列表模型表。如果您需要更多细节,请发表评论,我将编辑此帖子。

http://www.codeproject.com/Tips/668199/How-to-Cascade-Delete-an-Adjace