我有一个我想与LinqToSql查询层次:如何使用LinqToSQL查询层次结构?
国家 - >区域 - >市 - >邮编
每个实体都持有对它的引用的父(如Region.Country)和它的孩子的集合(例如Region.Cities)。
我想加载每个实体的父母以及国家和地区,但延迟加载城市和邮政编码。
使事情复杂化,每个实体在投影到模型之前都已被本地化。所以Country.Name根据语言而改变。
这里是什么,我至今一些片段:
public IQueryable<Country> ListCountries()
{
return ProjectCountry(dataContext.GetTable<ec_Country>());
}
private IQueryable<Country> ProjectCountry(IQueryable<ec_Country> query)
{
var result = from country in query
join localized in dataContext.GetTable<ec_CountryLocalization>() on country.CountryID equals localized.CountryID
let regions = GetRegions(country.CountryID)
where localized.StatusID == 4 && localized.WebSiteID == this.webSiteID
select new Country(country.CountryID) {
CreatedDate = country.CreatedDate,
IsDeleted = country.IsDeleted,
IsoCode = country.IsoCode,
Name = country.Name,
Regions = new LazyList<Region>(regions),
Text = localized.Text,
Title = localized.Title,
UrlKey = country.UrlKey
};
return result;
}
private IQueryable<Region> GetRegions(Int32 countryID)
{
var query = from r in dataContext.GetTable<ec_Region>()
where r.CountryID == countryID
orderby r.Name
select r;
return ProjectRegion(query);
}
private IQueryable<Region> ProjectRegion(IQueryable<ec_Region> query)
{
var result = from region in query
join localized in dataContext.GetTable<ec_RegionLocalization>() on region.RegionID equals localized.RegionID
join country in ListCountries() on region.CountryID equals country.CountryID
let cities = GetCities(region.RegionID)
select new Region(region.RegionID) {
Cities = new LazyList<City>(cities),
Country = country,
CountryID = region.CountryID,
CreatedDate = region.CreatedDate,
IsDeleted = region.IsDeleted,
IsoCode = region.IsoCode,
Name = region.Name,
Text = localized.Text,
Title = localized.Title,
UrlKey = region.UrlKey
};
return result;
}
...等
[TestMethod]
public void DataProvider_Correctly_Projects_Country_Spike()
{
// Act
Country country = dataProvider.GetCountry(1);
// Assert
Assert.IsNotNull(country);
Assert.IsFalse(String.IsNullOrEmpty(country.Description));
Assert.IsTrue(country.Regions.Count > 0);
}
测试失败:
System.NotSupportedException:方法体系。 Linq.IQueryable`1 [Beeline.EducationCompass.Model.Region] GetRegions(Int32)'不支持对SQL的转换。
你会如何推荐我去做这件事?如果层次结构的每个层次都在同一个表中而不是单独的表中,它会更简单(或可能)吗?
谢谢!这看起来很有希望。明天我会试一试。 – 2009-01-26 23:30:57