实体框架包括父实体

时间:2015-08-20 15:48:50

标签: c# linq entity-framework linq-to-entities

当我访问所有城市时,我的代码就是这样。

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

这很好,包括州和国家。我希望按国家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;
    }

2 个答案:

答案 0 :(得分:0)

你确定一个城市可以属于几个州吗?恕我直言,你应该有一对多的关系,其中State可以有多个Cities,而City应该属于一个StateStateCountry也是如此。我认为你已经复数了那些导航。属性名称(States中的CityCities中的Country)但没有收藏。如果您按照我上面描述的方式拥有这两个一对多的关系,您可以编写一个查询,如下所示,以实现您的需求:

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

最好使用DbExtensions.Include扩展方法,因为它是强类型的。

现在,也许你可以认为这个查询可以以NullReferenceException结尾,因为c.State.Country.Id表达式是其中一个导航。属性可以是null。但是这不会发生,因为当您需要保存新的City或者需要时,需要设置这些导航属性(或者在DB中已经存在的情况下的FK属性) DB中的State,换句话说,它们是必需的

如果您使用Fluent 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);

答案 1 :(得分: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集合 - 为什么你的City有一个{{1}收集和您的States有一个State集合?这些属性分别不应该是CountriesState属性吗?

假设您的Country确实只有一个City,并且您的State只有一个State,这会简化它:

Country
相关问题