我有Categories
及其subcategories
和stored procedure
我正在抓取所有这些并填写datatable
现在我想在我的课程中转换此数据表并且想要填写我的category
课程,如下所示:
表:分类
Id,Name,ParentId
存储过程: FetchAllCategories
with CTE as
(
select Id, Name, ParentId
from [dbo].[Category]
where ParentId = 0
union all
select c.Id, c.Name, c.ParentId
from [dbo].[Category] as c
join CTE as p on p.Id = c.ParentId
)
select * from CTE
order by Name
这是我的班级:
class category
{
public int Id;
public int ParentId;
public string Name;
public List<Category> Subcategories;
}
这是我的代码:
private static void ReadOrderData(string connectionString)
{
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand comm = new SqlCommand())
{
var dt = new DataTable();
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "FetchAllCategories";
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
dt.Load(reader);
var t = dt.AsEnumerable()
.Select
(
x => new category
{
ID = (int)(x["Id"]),
Name = (string)(x["Name"]),
//How to fill subcategory for specific category??
}
).ToList();
reader.Close();
conn.Close();
}
}
}
注意:我希望尽可能避免使用loops
。