You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Entity Framework Core 2.0与Dynamic Linq Core构建关联实体查询

Using Dynamic LINQ Core to Query Parts with Associated Warehouses in EF Core 2.0

Got it, let's break down how to retrieve Part objects with their linked Warehouse collections using Dynamic LINQ Core alongside EF Core 2.0.

First, make sure you've installed the Dynamic LINQ Core package via NuGet:

Install-Package System.Linq.Dynamic.Core
# Or for .NET CLI
dotnet add package System.Linq.Dynamic.Core

1. Eager Loading (Preload All Associated Warehouses)

If you want to fetch all Parts along with their full Warehouses collections upfront, use the Include method with a string that matches your navigation property name:

using System.Linq.Dynamic.Core;

// Assuming your DbContext has a DbSet<Part> called Parts
var partsWithWarehouses = context.Parts
    .Include("Warehouses") // Reference the navigation property by its exact name
    .ToList();

2. Filter Parts and Their Linked Warehouses

Dynamic LINQ lets you use string-based conditions to filter either the Parts themselves or their associated Warehouses:

Filter Parts That Have Warehouses Needing Reorder

var partsNeedingReorder = context.Parts
    .Include("Warehouses")
    .Where("Warehouses.Any(Quantity <= ReorderPoint)") // Check if any warehouse meets the reorder condition
    .ToList();

Project Parts with Filtered Warehouse Collections

To return Parts with only a subset of their Warehouses (e.g., only warehouses with in-stock items), use a dynamic Select projection:

var partsWithInStockWarehouses = context.Parts
    .Select(@"new (
        PartNumber,
        Description,
        Warehouses.Where(Quantity > 0) as Warehouses
    )")
    .ToList();

3. Explicit Loading (Load Warehouses After Fetching Parts)

If you already have a Part object and want to load its Warehouses later (with optional filtering), combine EF Core's entry API with Dynamic LINQ:

var specificPart = context.Parts.FirstOrDefault("PartNumber == 'P-123'");
if (specificPart != null)
{
    // Load only warehouses where quantity exceeds the reorder point
    context.Entry(specificPart)
        .Collection(p => p.Warehouses)
        .Query()
        .Where("Quantity > ReorderPoint")
        .Load();
}

Key Notes

  • Case Sensitivity: Dynamic LINQ uses exact property name matching, so ensure your string references (like "Warehouses") match the case of your entity class properties.
  • EF Core 2.0 Compatibility: Dynamic LINQ Core fully supports EF Core 2.0, but avoid using newer EF Core features that aren't compatible with your version.
  • Sorting: You can add dynamic sorting too, e.g., .OrderBy("PartNumber") to sort parts by their part number, or sort the warehouse collection directly in the projection.

内容的提问来源于stack exchange,提问作者jpico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:55:00