如何用mvc制作类别,子类别,子类别?

时间:2011-02-06 00:08:47

标签: asp.net-mvc linq-to-entities

我有三个班级

public class CountryListViewModel
{
    public IEnumerable<CountryViewModel>
    Countries { get; set; }
}

public class CountryViewModel
{
    public string CountryName { get; set; }
    public string State { get; set; }
    public IEnumerable<CityViewModel> Cities { get; set; }
}

public class CityViewModel
{
    public string CityName { get; set; }
    public string CityLink { get; set; }
}

使用linq按国家/地区进行实体分组,并按设计运行。 但我也必须按州分组。你能帮我改变一下我的问题,先按国家而不是按国家分组吗?

var query = from c in _db.MyTable
                        where c.IsActive && c.Country == country 
                        group c by c.Country
                            into loc
                            select new CountryViewModel()
                            {
                                CountryName = loc.Key,
                                Cities = loc.Select(s => new CityViewModel() { CityName = s.City, CityLink = s.City }).Distinct()
                            };

2 个答案:

答案 0 :(得分:1)

我自己找到了解决方案

var query = from c in _db.MyTable
            where c.IsActive && c.Country == country 
            group c by new{ c.Country, c.State}
            into loc
                    select new CountryViewModel()
                                {
                                    CountryName = loc.Key.Country,
    State = loc.Key.State,
                                    Cities = loc.Select(s => new CityViewModel() { CityName = s.City, CityLink = s.City }).Distinct()
                                };

答案 1 :(得分:0)

var q = from i in query 
        group i by i.state into st 
        select new with { .State = st.Key,
                          .Countries = (from c in st group c by c.Country into ctr 
                                        select new with {.Country = ctr.Key,
                                        .Cities = ctr})

不知道如果这样可行,只需在此处输入,而无需测试或查看您的数据模型。