【问题标题】:EF Core: Lambda expression used inside Include is not validEF Core:Include 中使用的 Lambda 表达式无效
【发布时间】:2020-06-05 01:05:54
【问题描述】:

我正在尝试获取所有活跃的Products (GetByCategory),包括所有活跃的ProductSpecifications,但没有成功。

如果我执行注释块,我会得到异常

System.InvalidOperationException:在 Include 中使用的 Lambda 表达式无效

我的解决方案是让所有活跃的Products,然后使用该方法加载所有活跃的ProductSpecifications

LoadAllActiveSpecifications(products)

使用LoadAllActiveSpecifications的问题是我需要运行一个for循环来加载所有规范。

是否可以隐式加载所有活动的ProductSpecification

这是我的代码。有人可以告诉我我缺少什么吗?

public async Task<IEnumerable<Product>> GetByCategory(string code)
{
    /*
    // Following the example from Microsoft: https://docs.microsoft.com/en-us/ef/core/querying/related-data
    return await _context
                    .Products
                    .Include(p => p.Category)
                    .Include(product => product
                                            .Specifications
                                            .Where(specification => specification.IsActive))
                    .Where(product => product.IsActive)
                    .Where(p => p.Category.Code == code)
                    .ToListAsync();
    */

    var products = await _context
                            .Products
                            .Include(p => p.Category)
                            //.Include(p => p.Specifications)
                            .Where(p => p.IsActive)
                            .Where(p => p.Category.Code == code)
                            .ToListAsync();

    await LoadAllActiveSpecifications(products);

    return products;
}

private async Task LoadAllActiveSpecifications(List<Product> products)
{
    for (int index = 0; index < products.Count; index++)
    {
        var product = products[index];

        await LoadSpecActiveAsync(product);
    }
}

private async Task LoadSpecActiveAsync(Product product)
{
    await _context
            .Entry(product)
            .Collection(p => p.Specifications)
            .Query()
            .Where(s => s.IsActive)
            .LoadAsync();
}

提前致谢

干杯

【问题讨论】:

  • 这段代码遇到了什么问题?
  • 我觉得我以前见过这个问题。您是否尝试过将 Where 子句移到 Include 之外?此外,如果 Specifications 映射到另一个表,您可能需要在 Where 之前添加 ThenIncludes
  • @ChetanRanpariya 我收到了那个错误 System.InvalidOperationException: Include 中使用的 Lambda 表达式无效。谢谢
  • 嘿@DillonDrobena,我都试过了,但没有成功。我的情况的解决方案是在我的上下文中设置一个全局过滤器:modelBuilder.Entity&lt;ProductSpecification&gt;().HasQueryFilter(p =&gt; p.IsActive);,因为史蒂夫发布了链接。谢谢

标签: c# .net entity-framework asp.net-core


【解决方案1】:

根据定义,EF 将加载完整的实体图。您可以在 EF Core (https://docs.microsoft.com/en-us/ef/core/querying/filters) 中分配全局查询过滤器来处理诸如软删除之类的规则,这将允许 EF 仅返回适用实体的“活动”行。 EF6 在动态查询中有类似的东西。

【讨论】:

  • 谢谢@steve-py。我将过滤器设置为链接,它就像一个魅力。这是我的案例的解决方案:modelBuilder.Entity&lt;ProductSpecification&gt;().HasQueryFilter(p =&gt; p.IsActive);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
相关资源
最近更新 更多