如何从数据表中按特定类别填充子类别?

时间:2016-06-22 11:03:15

标签: c# .net linq datatable ado.net

我有Categories及其subcategoriesstored procedure我正在抓取所有这些并填写datatable现在我想在我的课程中转换此数据表并且想要填写我的category课程,如下所示:

enter image description here

表:分类

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

0 个答案:

没有答案