基于.net的NHibernate框架 获取所有省市区

实体-------------------------------

/// <summary>
/// 区域表
/// </summary>
public class Area : EntityBase
{
public virtual string Name { get; set; }
public virtual Area Parent { get; set; }

}

 

 

接口--------------------------------

public class AreaQuery : QueryBase
{
}
public interface IAreaRepository : IRepository<Area>
{
IList<Area> GetByParentId(int id);

IList<Area> GetByName(string name);

/// <summary>
/// 获取全部省级区域
/// </summary>
/// <returns></returns>
IList<Area> GetAllProvince();

/// <summary>
/// 根据父级ID获取下级区域
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
IList<Area> GetSonAreaByParentId(int pid);
}

 

 

接口实现------------------------

public class AreaRepository : Repository<Area>, IAreaRepository
{
protected override IQueryable<Area> LoadQuery<TQ>(TQ query)
{
var q = base.LoadQuery(query);
var uq = query as AreaQuery;
return q;
}
public IList<Area> 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<Area> GetByName(string name)
{
return Query.Where(c => c.Name.Contains(name)).ToList();
}

/// <summary>
/// 获取全部省级区域
/// </summary>
/// <returns></returns>
public IList<Area> GetAllProvince()
{
return Query.Where(c => c.Parent == null).ToList();
}

/// <summary>
/// 根据父级ID获取下级区域
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public IList<Area> 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 List<NewArea> AreaList { get; set; }
}

public class NewArea
{
public int Id { get; set; }
public string Name { get; set; }
}

/// <summary>
/// 获取所有省市区
/// </summary>
/// <returns></returns>
[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<NewCity> GetCityList(Area a)
{
List<NewCity> _list = new List<NewCity>();
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<NewArea> GetAreaList(Area a)
{
List<NewArea> _list = new List<NewArea>();
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

 

posted @ 2021-12-08 16:06  吃兔子的萝卜7  阅读(50)  评论(0编辑  收藏  举报