我需要能够以特定顺序订购帐户列表。它们都具有一级父/子关系。
所以,数据看起来像这样:
AccountID AccountName ParentID
1 Blue NULL
2 Red NULL
3 Green NULL
4 Yellow 3
5 Orange 2
6 Purple 1
7 Voilet 1
8 Gold 2
etc...
我需要填充一个下拉列表,如下所示(如下),该列表由 AccountID 排序,其父 ID 为 NULL,首先按字母顺序排列,然后任何子帐户都按字母顺序排列。儿童帐户上的“破折号”只是为了视觉效果而添加的,所以不用担心。
Blue
- Purple
- Voilet
Green
- Yellow
Red
- Gold
- Orange
这是我之前使用的代码(如下),但是在大约 30 个帐户之后它开始给我这个错误。
您的 SQL 语句的某些部分嵌套得太深。重写查询或将其分解为更小的查询。
Public Function GetAllActiveAccountsForAccountSwitcher() As IEnumerable(Of Models.AccountDropDownListModel)
Dim isFirst As Boolean = True
Dim list As IQueryable(Of Models.AccountDropDownListModel) = Nothing
Dim parentAccts As IQueryable(Of Account) = From a As Account In dc.Accounts _
And a.ParentID Is Nothing _
Order By a.AccountName
For Each parentAcct In parentAccts
Dim parent = From a In dc.Accounts Where a.AccountID = parentAcct.AccountID _
Select New Models.AccountDropDownListModel _
With { _
.AccountID = a.AccountID,
.AccountName = a.AccountName
}
If isFirst Then
list = parent
isFirst = False
Else
list = list.Union(parent)
End If
Dim child = From a As Account In dc.Accounts Where a.ParentID = parentAcct.AccountID _
Select New Models.AccountDropDownListModel _
With { _
.AccountID = a.AccountID,
.AccountName = "- " & a.AccountName
}
list = list.Union(child)
Next
Return list
End Function
C# 或 VB.NET 示例很好。我不知道,但它需要使用 linq-to-sql。存储过程不是我的情况的选择。
更新: 对于对 VB 过敏的人来说,这是我的原始代码的 c#...
public IEnumerable<Models.AccountDropDownListModel> GetAllActiveAccountsForAccountSwitcher()
{
bool isFirst = true;
IQueryable<Models.AccountDropDownListModel> list;
IQueryable<Account> parentAccts = from a in dc.Accounts & a.ParentID == null orderby a.AccountName;
foreach (void parentAcct_loopVariable in parentAccts) {
parentAcct = parentAcct_loopVariable;
var parent = from a in dc.Accountswhere a.AccountID == parentAcct.AccountID select new Models.AccountDropDownListModel {
AccountID = a.AccountID,
AccountName = a.AccountName
};
if (isFirst) {
list = parent;
isFirst = false;
} else {
list = list.Union(parent);
}
var child = from a in dc.Accountswhere a.ParentID == parentAcct.AccountID select new Models.AccountDropDownListModel {
AccountID = a.AccountID,
AccountName = "- " + a.AccountName
};
list = list.Union(child);
}
return list;
}