简体   繁体   English

Linq查询分组父母和各自的子女租金

[英]Linq Query to group Parent and respective child rentities

Here are my classes: 这是我的课程:

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

I am having difficulty in creating the query that will give me all the records for each entities above grouped by Country, then State, then County, then City 我在创建查询时遇到困难,该查询将为我提供按国家/地区分组的每个实体的所有记录,然后是州,然后是县,然后是城市

I am ultimately trying to put this into a backbone.js treeview. 我最终试图把它放到backbone.js树视图中。

What would be the correct Linq query for collecting the records in their respective groups 在各自的组中收集记录的正确Linq查询是什么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM