【问题标题】:EF Core Include, Where, and ThenIncludeEF Core Include、Where 和 ThenInclude
【发布时间】:2019-07-31 18:41:08
【问题描述】:

我必须从数据库中收集数据,其中删除的记录并未真正删除,而是被标记(有一个“IsActive”位列,其中已删除的项目保存值为 0)。

我正在使用 Entity Framework Core,我想获取货币列表(欧元、美元、...)。每种货币都与 1-n 个国家/地区相关联,因此这里有 3 个列在起作用:

  • 货币(ID、姓名、...)
  • CurrencyCountry(CurrencyId、CountryNumericCode)
  • 国家(数字代码、姓名、...)

我想在一次 ef 调用中获取所有货币及其国家/地区;所以我确实有类似的东西:

_ctx.Currency
.Where(c => c.IsActive)
.Include(c => c.CurrencyCountry)
.ThenInclude(cc => cc.CountryNumericCodeNavigation)
.ToList();

这几乎可以工作;唯一的问题是我需要指定我只想要活动的“CurrencyCountries”。所以我想在“Include”之后和“ThenInclude”之前添加一个“Where IsActive == true”,但看起来无法完成。

还有其他方法可以完成我想做的事情吗?

谢谢!

【问题讨论】:

  • 我想你可能需要在某个地方做任何事情

标签: entity-framework asp.net-core .net-core hyperlink


【解决方案1】:

您是否尝试过从联结表而不是 Currency 开始查询?

ctx.CurrencyCountry
.Include(c => c.Currency)
.Include(c => c.Country)
.Where(c => c.Country.IsActive && c.CurrencyCountry.IsActive)
.ToList();

【讨论】:

  • 感谢您的建议。我需要一个货币列表(但我可以在应用程序中转换列表?)。此解决方案的另一个问题是,如果存在没有关联国家/地区的货币,它们将不会出现在列表中。
【解决方案2】:

所以我想在“Include”之后和“ThenInclude”之前添加一个“Where IsActive == true”,但看起来无法完成。

这个话题仍在进行中的讨论: https://github.com/aspnet/EntityFrameworkCore/issues/1833

一种解决方法是您可以在Select 中手动过滤数据,这有点复杂:

_ctx.Currency
    .Where(c => c.IsActive)
    .Include(c => c.CurrencyCountry)
    .ThenInclude(cc => cc.CountryNumericCodeNavigation)
    .Select(c => new Currency
    {
        //populate other fields in Currency model here
        CurrencyCountry = c.CurrencyCountry.Where(item => item.IsActive).ToList()
    })
    .ToList();

【讨论】:

    【解决方案3】:

    免责声明:我是项目的所有者Entity Framework Plus

    EF+ Query IncludeFilter(免费和开源)允许轻松过滤包含的实体。

    尚不支持ThenInclude,但您只需包含最后一个过滤器即可获得相同的行为。

    例子:

    _ctx.Currency
    .Where(c => c.IsActive)
    .IncludeFilter(c => c.CurrencyCountry.Where(c => c.IsActive))
    .IncludeFilter(c => c.CurrencyCountry.Where(c => c.IsActive).Select(cc => cc.CountryNumericCodeNavigation))
    .ToList();
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 2020-08-24
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多