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

如何使用Ardalis Specification获取关联记录的ID列表

使用Ardalis Specification获取关联记录的ID列表

当然可以,完全不需要加载完整的Building实体,通过**投影(Projection)**就能仅获取关联的Building ID列表,这种方式还能减少数据库查询的数据量,提升性能。

方式一:获取包含Building ID列表的Project信息

先定义一个DTO用于承载结果:

public class ProjectWithBuildingIdsDto
{
    public long ProjectId { get; set; }
    public string ProjectName { get; set; }
    public List<long> BuildingIds { get; set; }
}

然后编写对应的Specification,通过Select进行投影:

public sealed class ProjectWithBuildingIdsSpecification : Specification<ProjectEntity, ProjectWithBuildingIdsDto>
{
    public ProjectWithBuildingIdsSpecification(long projectId)
    {
        Query
            .AsNoTracking()
            .Where(x => x.Id == projectId)
            .Select(project => new ProjectWithBuildingIdsDto
            {
                ProjectId = project.Id,
                ProjectName = project.ProjectName,
                BuildingIds = project.Buildings.Select(b => b.BuildingId).ToList()
            });
    }
}

方式二:仅获取Building ID列表

如果不需要Project的其他信息,直接投影出Building ID集合即可:

public sealed class ProjectBuildingIdsSpecification : Specification<ProjectEntity, List<long>>
{
    public ProjectBuildingIdsSpecification(long projectId)
    {
        Query
            .AsNoTracking()
            .Where(x => x.Id == projectId)
            .SelectMany(project => project.Buildings.Select(b => b.BuildingId));
    }
}

说明

上述两种方式都会让EF Core在数据库层面仅查询BuildingId字段,不会加载完整的Building实体,比原代码中Include(x => x.Buildings)的方式更高效。只要你的DbContext已正确配置Project与Building的一对多导航关系,就能正常生成对应的SQL语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:52:15