我有一个数据库表,它表示具有多层次层次结构的帐户。每一行都有一个"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
};发布于 2013-10-14 19:54:36
您当前的结构实际上是一个层次结构(一个邻接列表模型)。问题是,你想要保持这个层次模型吗?如果你这样做了,有一个名为MVCTreeView的Nuget包。这个包直接与您描述的表结构一起工作--在它中,您可以为您的UI创建一个树视图,在每个级别上实现CRUD操作等等。我必须这样做,我写了一篇关于CodeProject的文章,展示了如何通过C#级联删除SQL中的邻接列表模型表。如果您需要更多的细节,请留下评论,我将编辑这篇文章。
http://www.codeproject.com/Tips/668199/How-to-Cascade-Delete-an-Adjace
发布于 2013-10-14 19:49:27
您只需为父键创建一个关联属性:
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();https://stackoverflow.com/questions/19367727
复制相似问题