2015-08-20 226 views
0

當我訪問所有城市時,我的代碼就像這樣。實體框架包含父實體

public IQueryable<City> GetAll() 
    { 
     var result = from s in this.Context.Cities.Include("States.Countries") select s; 
     return result; 
    } 

這工作正常,包括狀態和countires。我想通過國家ID獲取城市,下面是我的代碼。在下面的代碼中,我想包含每個城市的States.Countires。我怎樣才能做到這一點 ?

public IEnumerable<City> GetByCountriesId(int Id) 
    { 
     var result = from s in this.Context.Countries 
        join a in this.Context.States on s.Id equals a.Country_Id 
        join b in this.Context.Cities on a.Id equals b.States_Id 
        where s.Id == Id 
        select b; 

     return result; 
    } 
+3

'this.Context.Cities.Include( 「State.Country」)。如果「City」和「State」具有適當的導航屬性,那麼(c => c.State.Country.Id == Id)'就足夠了。 –

+0

你使用什麼版本的EF?我問,因爲包含你使用的字符串參數是舊的,你應該使用表達式方法來支持編譯時。例如:'.Include(x => x.States)' –

回答

0

你確定一個城市可以屬於幾個州嗎?恕我直言,你應該有一對多的關係,其中State可能有幾個CitiesCity應該屬於一個StateStateCountry也是如此。我認爲你已經複製了那些導航。物業名稱(中的StatesCountry中的Cities),但沒有集合。如果你有這兩個一個在我上面描述的同樣的方式很多關係,可以編寫一個查詢,我展示如下達到你需要的東西:

var result = this.Context.Cities.Include(c=>c.State.Country).Where(c=>c.State.Country.Id==Id‌​); 

更好使用DbExtensions.Include擴展方法,因爲是強類型的。

現在,也許你可以認爲這個查詢可能以NullReferenceException結尾,因爲這些nav中的一個是c.State.Country.Id表達式。屬性可能是null。但是這不會發生,因爲當需要在數據庫中保存新的CityState時,需要設置這些導航屬性(或者FK屬性已存在於數據庫中),換句話說,他們是要求

如果使用流暢API來配置這些關係你會是這樣結束:

modelBuilder.Entity<City>().HasRequired(c=>c.State).WithMany(s=>s.Cities).HasForeignKey(c=>c.State_Id); 
modelBuilder.Entity<State>().HasRequired(s=>s.Country).WithMany(c=>c.States).HasForeignKey(s=>s.Country_Id); 
0
public IEnumerable<City> GetByCountriesId(int id) 
{ 
    return from country in this.Context.Countries 
      where country.Id == id 
      from state in country.States 
      from c in this.Context.Cities.Include(c => c.States.Select(s => s.Countries)) 
      where c.States.Any(s => s == state) 
      select c; 
} 

,或者甚至更好:

public IEnumerable<City> GetByCountryId(int id) 
{ 
    return from c in this.Context.Cities 
        .Include(c => c.States.Select(s => s.Countries)) 
      where c.States.Any(s => s.Countries.Any(c => c.Id == id)) 
      select c; 
} 

然而–雖然這是很清楚,爲什麼Country有一個States集合和State有一個Cities集合–爲什麼您的CityStates集合,您的StateCountries集合嗎?不應該分別是StateCountry屬性嗎?

假設你City確實有一個State,和你的State有一個Country,這簡化了很多:

return from c in this.Context.Cities 
       .Include(c => c.State.Select(s => s.Country)) 
     where c.State.Country.Id == id 
     select c;