简体   繁体   English

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

[英]How to determine if a related child-entity has been included

I have a web application built with ASP.NET Core / EF Core with two entities "Products" and "ProductOptions" (one-to-many relationship). 我有一个使用ASP.NET Core / EF Core构建的Web应用程序,带有两个实体“ Products”和“ ProductOptions”(一对多关系)。

When I execute a query to retrieve a Product from the database, is there a way to determine if the related ProductOptions (children of Product) have been included or not? 当我执行查询以从数据库中检索产品时,是否可以确定是否包含相关的ProductOptions(产品的子级)? I need to distinguish between the following cases: 我需要区分以下情况:

Case 1: a Product's related ProductOptions have been included in the query, but no ProductOptions have been found 情况1:查询中包含产品的相关ProductOptions,但未找到ProductOptions

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

Case 2: a Product's related ProductOptions haven't been included at all 情况2:根本不包含产品的相关ProductOptions

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

You can use ChangeTracker to check if reference is loaded. 您可以使用ChangeTracker来检查引用是否已加载。 You probably want to do something like: 您可能想要执行以下操作:

var isLoaded = dbContext.ChangeTracker.Entries<Products>()
    .FirstOrDefault(ee => ee.Entity == product)
    .Reference(e => e.ProductOptions)
    .IsLoaded;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM