天天看點

基于.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      

本文來自部落格園,作者:康Sir7,轉載請注明原文連結:https://www.cnblogs.com/kangsir7/p/15662073.html