2012-11-07 43 views
0

这里是我的课:LINQ查询到集团母公司和各子rentities

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 treeview。

什么是正确的Linq查询在各自小组收集记录数据

+2

你想怎么组记录?我期待的是一个包含国家,州,县和城市的客户记录,以便您可以按国家,州,县,城市对客户进行分组。 – Kristof

回答

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; 
    }