【发布时间】: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<ProductSpecification>().HasQueryFilter(p => p.IsActive);,因为史蒂夫发布了链接。谢谢
标签: c# .net entity-framework asp.net-core