如何确定是否包含相关的子实体

问题描述 投票:0回答:1

我有一个使用ASP.NET Core / EF Core构建的Web应用程序,它包含两个实体“Products”和“ProductOptions”(一对多关系)。

当我执行查询以从数据库中检索产品时,有没有办法确定是否包含了相关的ProductOptions(Product of Children)?我需要区分以下情况:

案例1:产品的相关ProductOptions已包含在查询中,但未找到ProductOptions

public Product GetByIdIncludingProductOptions(int id)
{
    return DbContext.Products.Include(p => p.ProductOptions).FirstOrDefault(p => p.Id == id);
}

案例2:产品的相关ProductOptions尚未包含在内

public Product GetById(int id)
{
    return DbContext.Products.FirstOrDefault(p => p.Id == id);
}
c# asp.net-core entity-framework-core
1个回答
2
投票

您可以使用ChangeTracker检查是否加载了引用。你可能想做类似的事情:

var isLoaded = dbContext.ChangeTracker.Entries<Products>()
    .FirstOrDefault(ee => ee.Entity == product)
    .Reference(e => e.ProductOptions)
    .IsLoaded;
© www.soinside.com 2019 - 2024. All rights reserved.