Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在LINQ中创建层次结构_C#_Linq - Fatal编程技术网

C# 在LINQ中创建层次结构

C# 在LINQ中创建层次结构,c#,linq,C#,Linq,我有一个数据库表,它表示具有多级层次结构的帐户。每行都有一个“AccountKey”,表示当前帐户,可能还有一个“ParentKey”,表示父帐户的“AccountKey” 我的模型类是“AccountInfo”,它包含一些关于帐户本身的信息,以及一系列子帐户 将这个平面数据库结构转换为层次结构的最简单方法是什么?它可以直接在LINQ中完成,还是需要在事后循环并手动构建 型号 public class AccountInfo { public int AccountKey { get;

我有一个数据库表,它表示具有多级层次结构的帐户。每行都有一个“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; } 
}

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

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

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


因此,您拥有的是SQL中的邻接列表模型(通过ParentId在单个表中维护层次结构)。是否要将此表转换为其他结构,或保留现有结构(具有parentId的单个表)?
var children = context.Accounts
    .Where(a => a.AccountKey = someKey)
    .SelectMany(a => a.Children)
    .ToArray();