我有一個我想與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