2015-08-20 230 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;