【问题标题】:Selecting parents of children who meet certain criteria选择符合特定标准的孩子的父母
【发布时间】:2019-06-10 11:49:14
【问题描述】:

所以,我从我的数据库中检索了一堆国家:

var countries = dbContext.Countries.toList();

然后,根据程序流程,我进一步过滤这些 Contries:

var asianContries = result.where(c=>c.continent == "asia").toList();

My Country 表是 Cities 表的“父”表,每个城市都与一个国家/地区相关联。城市表包含人口信息,我想进一步过滤。

我想要从已过滤的“asianCountries”列表对象中获得人口超过 500,000 的城市的国家/地区列表。我只是想弄清楚该怎么做。另外,我对这些东西不熟悉。

为什么要进行多步过滤,而不是一次性选择所有条件?程序流程的复杂性。很长的故事。 :-)

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    如果我理解正确,您现在已经过滤到亚洲国家,您想进一步过滤这些结果。 如果您将人口设为 int,我会选择两种方法之一

    var cities = asianCountries.Select(x => x.cities.Where( y => y.population > 500000)).ToList();
    

    如果是字符串则

    var cities = asianCountries.Select(x => x.cities.Where(y => Convert.ToInt32(y.population) > 500000)).ToList();
    

    我认为这应该可行。

    【讨论】:

      【解决方案2】:

      连接多个表的示例,

      from ct in dbContext.Countries
                join ci in dbContext.Cities on ct.CityID equals ci.ID
                where (ct.continent == "asia") && (ci.Population == // yourCondition) 
                select new { country = ct.Name, city = ci.Name , // other fields you want to select
                           };
      

      您可以参考如何连接多个表here

      【讨论】:

      • 宁愿避免连接并让 EntityFramework 处理它,因为关系已经在我的模型模式中定义。另外,我需要从已经减少的 asianCountries 列表对象中进行选择,而不是从整个 dbContext.Countries 对象中进行选择。
      • @jjespersen,relations are already defined in my Model schema。然后@Haldo 回答会帮助你
      【解决方案3】:

      如果对象实现IQueryable<T>,则仅在枚举对象时执行查询。这意味着您可以将查询链接在一起,并且将延迟执行,直到您调用,例如ToList()

      在您的示例中,您可以执行以下操作:

      // to select the cities
      var largeCities = dbContext.Countries
                                 .Include(t => t.Cities)
                                 .Where(c=> c.continent == "asia" 
                                        && c.Cities.Population > 500000)
                                 .Select(c => c.Cities).ToList();
      
      // EDIT
      // to select the countries that have these cities
      var countries = dbContext.Countries
                                 .Include(t => t.Cities)
                                 .Where(c=> c.continent == "asia" 
                                        && c.Cities.Population > 500000)
                                 .ToList();  // remove .Select(c => C.Cities) if you want the countries
      

      或者

      var largeCities = asianCountries
                             .Where(c => c.Cities.Population > 500000)
                             .Select(c => c.Cities)
                             .ToList();
      

      【讨论】:

      • 问题是在第二个示例的第 2 行中无法访问 Population 属性。在下面的答案中找到了解决方案。 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2015-08-30
      • 2020-11-16
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多