在 Web API 控制器中使用显式加载来加载相关实体。以下是一个示例:
[HttpGet("{id}")]
public async Task> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
// 显式加载 RelatedProducts 集合
await _context.Entry(product)
.Collection(p => p.RelatedProducts)
.LoadAsync();
return product;
}
在上面的代码中,显式加载了 RelatedProducts
集合,这可以确保在返回 Product
对象时该集合已被加载。这种方法可以确保 Web API 返回完整的实体,而不仅仅是使用懒加载提取的部分属性。