0

这是我的课程:

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 查询来收集各自组中的记录

4

1 回答 1

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;
    }
于 2012-11-09T11:54:22.860 回答