以下是我的课程:
class Country
{
public Country()
{
States = new List<State>();
}
public int Id { get; set; }
public int Name { get; set; }
public virtual ICollection<State> States { get; set; }
}
class State
{
public State()
{
Counties = new List<County>();
}
public int Id { get; set; }
public int Name { get; set; }
public int CountryID { get; set; }
[ForeignKey("CountryID")]
public virtual Country Country { get; set; }
public virtual ICollection<County> Counties { get; set; }
}
class County
{
public County()
{
Cities = new List<City>();
}
public int Id { get; set; }
public int Name { get; set; }
public int StateID { get; set; }
[ForeignKey("StateID")]
public virtual State State { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
class City
{
public int Id { get; set; }
public int Name { get; set; }
public int CountyID { get; set; }
[ForeignKey("CountyID")]
public virtual County County { get; set; }
}
我在创建查询时遇到困难,该查询将为我提供按国家/地区分组的每个实体的所有记录,然后是州,然后是县,然后是城市
我最终试图把它放到backbone.js树视图中。
在各自的群组中收集记录的正确Linq查询是什么
答案 0 :(得分:2)
public List<Country> GetCountryHeiracrchy()
{
var countries = DbContext.GetAll();
var lstCountries = new List<Country>();
foreach (var _country in countries)
{
var country = new Country { Name = _country.Name };
foreach (var _state in _country.States)
{
var state = new State() {Name = _state.Name};
foreach(var _county in _state.Counties)
{
var county = new County {Name = _county.Name};
foreach(var _city in _county.Cities)
{
var city = new City {Name = _city.Name};
county.Cities.Add(city);
}
state.Counties.Add(county);
}
country.States.Add(state);
}
lstCountries.Add(country);
}
return lstCountries;
}