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

Entity Framework中如何同时加载Auto的多个关联实体?

Hey there! I see you're trying to load two related entities (Eigenaar and AutoType) for your Auto class in EF Core, but ran into issues with IIncludableQueryable's generic parameter limit and incorrect use of ThenInclude. Let's break this down and fix it.

What Went Wrong in Your Original Code

Your mistake was using ThenInclude for HuidigeEigenaar — that method is designed for nested related entities (like if AutoType had its own associated property you wanted to load). But HuidigeEigenaar is a direct navigation property on Auto, not on AutoType. Combine that with IIncludableQueryable only supporting two generic parameters, and you ended up with invalid code.

The Simple Fix: Multiple Include Calls

To load multiple independent related entities, you just need to call Include separately for each direct association on your main entity. No need for ThenInclude here, since these are two separate top-level relationships.

Corrected GetFullyGraphedAutos Method

Here are two valid options, depending on whether you want to keep using IIncludableQueryable or simplify to IQueryable:

// Option 1: Simplest approach - return IQueryable<Auto>
private IQueryable<Auto> GetFullyGraphedAutos()
{
    return _entityContext.Autos
        .Include(x => x.HuidigeAutoType) // Loads AutoType for each Auto
        .Include(x => x.HuidigeEigenaar); // Loads Eigenaar for each Auto
}

// Option 2: Use IIncludableQueryable with object for type consistency
private IIncludableQueryable<Auto, object> GetFullyGraphedAutos()
{
    return _entityContext.Autos
        .Include(x => x.HuidigeAutoType)
        .Include(x => x.HuidigeEigenaar);
}

Update Your Existing Method

Your GetAllAutosSortedByName method will work seamlessly with the corrected GetFullyGraphedAutos:

public List<Auto> GetAllAutosSortedByName(AutoCriteria criteria)
{
    return GetFullyGraphedAutos()
        .Where(x => string.IsNullOrEmpty(criteria.Name)) // Note: Adjust this if you want to filter by owner name!
        .OrderBy(x => x.Id)
        .ToList();
}

Quick Note on the Filter Logic

Right now, your Where clause only returns autos when criteria.Name is empty. If you intended to filter by the owner's full name, update the condition to:

.Where(x => string.IsNullOrEmpty(criteria.Name) || x.HuidigeEigenaar.Naam.Contains(criteria.Name))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:29:37