基于.net的NHibernate框架 获取所有省市区
实体-------------------------------
////// 区域表 /// public class Area : EntityBase { public virtual string Name { get; set; } public virtual Area Parent { get; set; } }
接口--------------------------------
public class AreaQuery : QueryBase { } public interface IAreaRepository : IRepository { IList GetByParentId(int id); IList GetByName(string name); ////// 获取全部省级区域 /// /// IList GetAllProvince(); /// /// 根据父级ID获取下级区域 /// /// /// IList GetSonAreaByParentId(int pid); }
接口实现------------------------
public class AreaRepository : Repository, IAreaRepository { protected override IQueryable LoadQuery(TQ query) { var q = base.LoadQuery(query); var uq = query as AreaQuery; return q; } public IList GetByParentId(int id) { if (id == 0) { return Query.Where(c => c.Parent == null).ToList(); } else { return Query.Where(c => c.Parent.Id == id).ToList(); } } public IList GetByName(string name) { return Query.Where(c => c.Name.Contains(name)).ToList(); } /// /// 获取全部省级区域 /// /// public IList GetAllProvince() { return Query.Where(c => c.Parent == null).ToList(); } /// /// 根据父级ID获取下级区域 /// /// /// public IList GetSonAreaByParentId(int pid) { return Query.Where(c => c.Parent.Id == pid).ToList(); } }
控制器----------------------------
#region 获取全部省市区 public class NewCity { public int Id { get; set; } public string Name { get; set; } public ListAreaList { get; set; } } public class NewArea { public int Id { get; set; } public string Name { get; set; } } /// /// 获取所有省市区 /// /// [HttpPost] public ActionResult GetAllAreas() { var _p = AreaRepository.GetAllProvince(); if (_p.Count > 0) { foreach (var item in _p) { var o = from u in _p select new { Id = u.Id, Name = u.Name, CityList = GetCityList(u) }; return Json_IsoksSuccess(o); } } return Json_IsoksError("暂无数据"); } private List GetCityList(Area a) { List _list = new List (); var _city_list = AreaRepository.GetSonAreaByParentId(a.Id); foreach (var item in _city_list) { NewCity _na = new NewCity(); _na.Id = item.Id; _na.Name = item.Name; _na.AreaList = GetAreaList(item); _list.Add(_na); } return _list; } private List GetAreaList(Area a) { List _list = new List (); var _city_list = AreaRepository.GetSonAreaByParentId(a.Id); foreach (var item in _city_list) { NewArea _na = new NewArea(); _na.Id = item.Id; _na.Name = item.Name; _list.Add(_na); } return _list; } #endregion