アカウントのリストを特定の順序で注文できるようにする必要があります。それらはすべて、1 レベルの親子関係を持っています。
したがって、データは次のようになります。
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;
}