【发布时间】:2013-09-26 00:41:40
【问题描述】:
我需要能够按特定顺序订购帐户列表。它们都具有一级父/子关系。
所以,数据看起来像这样:
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...
我需要填充一个下拉列表,如下所示(如下),该列表由具有 NULL ParentID 的 AccountID 首先按字母顺序排序,然后是该父项的任何子帐户,也按字母顺序排序。子账号上的“破折号”只是为了视觉效果而添加的,所以不用担心。
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;
}
【问题讨论】:
标签: .net linq-to-sql