我有一个使用 EFCore 5 的 LINQ 查询,它急切地加载多个级别的相关实体。在其中一个中,我需要根据顶级实体上的字段过滤引用的实体,有没有办法做到这一点?
我想要的查询,但在 Where
中除外 我如何引用 product
?
context.Products
.Include(product => product.PrimaryComponent)
.ThenInclude(component => component.ComponentRules
.Where(cRule => cRule.FactoryId == product.FactoryId))
.Where( /* other filters */ )
在 Where()
表达式中我可以引用 cRule
和 component
但我不能引用 product
.
表格:
dbo.Product ( Id int, FactoryId int, PrimaryComponentId int )
dbo.Component ( Id int, Name nvarchar(100) )
dbo.ComponentRule ( ComponentId int, RuleId int, FactoryId int, Notes nvarchar(max) )
-- These tables aren't used in these queries but here they are fyi:
dbo.Rule ( Id int, Name nvarchar(100), ... )
dbo.Factory ( Id int, Name nvarchar(100), ... )
在这个数据库中,产品使用组件,每个组件都有许多关联的规则,具体取决于我们谈论的是哪个工厂。每个产品仅在一个工厂中构建,因此当我获得 ComponentRule 对象时,我只想加载与产品的 FactoryId 相关的对象,而不是所有工厂的所有 ComponentRules。每个组件仍然会有几个 ComponentRules,只是没有那么多。
如果我要编写一个 SQL 查询,我的想法是:
select *
from dbo.Product
inner join dbo.Component
on Product.PrimaryComponentId = Component.Id
inner join dbo.ComponentRule
on Component.Id = ComponentRule.ComponentId
-- The line below is the tricky one:
and ComponentRule.FactoryId = Product.FactoryId
-- ... plus other filters
where
我不能轻易地只为它编写 SQL,因为我实际上是在引入其他几个实体并使用 .AsSplitQuery()
来提高效率。所以我真的很想能够从 .ThenInclude(...)
中引用顶级 Product.FactoryId
。有什么办法吗?
最佳答案
UPD:假设您的模型是:
// in your OnModelCreating()
modelBuilder.Entity<ComponentRule>()
.HasOne(p => p.Component)
.WithMany(b => b.ComponentRules);
public class Product
{
public int Id { get; set; }
public int FactoryId { get; set; }
public int PrimaryComponentId { get; set; }
public Component PrimaryComponent { get; set; }
}
public class Component
{
public int Id { get; set; }
public string Name { get; set; }
public List<ComponentRule> ComponentRules { get; set; }
}
public class ComponentRule
{
public int ComponentId { get; set; }
public Component Component { get; set; }
public int FactoryId { get; set; }
}
也许你可以这样做:
context.Products
// 'Include's are not needed for LINQ query with custom projection (thanks Svyatoslav Danyliv)
// .Include(product => product.PrimaryComponent)
// .ThenInclude(component => component.ComponentRules)
.Where( /* other filters */ )
.Select(product => new Product {
Id = product.Id,
FactoryId = product.FactoryId,
PrimaryComponent = new Component {
Id = product.PrimaryComponent.Id,
Name = product.PrimaryComponent.Name,
ComponentRules = product.PrimaryComponent.ComponentRules
.Where(r => r.FactoryId == product.FactoryId).ToList()
},
})
关于c# - 在 EFCore 预加载 LINQ 查询中,如何在 ThenInclude() 表达式中引用顶级实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68275839/