.net使用递归构建树形数据

1、新建一个MVC项目(添加EntityFramework.dll与System.Date.Entity.dll),采用CodeFist建立数据库

2、在Models文件夹下新建三个类,第一个数据体实体类(),第二个上下文对象DbContext,第三个就是树形结构类

(1)数据实体类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Demo.Models
{
public class TestModel
{
[Key]
public int Id { get; set; }
[StringLength(50)]
public string Name { get; set; }
public int Pid { get; set; }
}
}

 

(2)上下文对象

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace Demo.Models
{
public class MyDbContext:DbContext
{
public MyDbContext():base("name=MyCollection")
{

}
public DbSet<TreeModel> TreeModel { get; set; }
}
}

(3)树形结构类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo.Models
{
public class TreeModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<object> Children = new List<object>();
}
}

 

看一下数据库表

 

3、新建一个控制器

using Demo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Demo.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
List<TreeModel> a = GetTree(0);//得到1级或多级树形数据
return View();
}
public List<TreeModel> GetTree(int id)
{
List<TreeModel> cmbTreeList = new List<TreeModel>();
using (DbContext db = new MyDbContext())
{
var parentList = db.Set<TestModel>().Where(t => t.Pid == id).ToList();

foreach (var item in parentList)
{
TreeModel treeModel = new TreeModel();
treeModel.Id = item.Id;
treeModel.Name = item.Name;
treeModel.Children.AddRange(GetTree(treeModel.Id));
cmbTreeList.Add(treeModel);
}
}
return cmbTreeList;
}
}
}

 

posted @ 2017-01-20 17:49  南京夜空中最亮的星  阅读(1225)  评论(0编辑  收藏  举报