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

ASP.NET Boilerplate中AsyncCrudAppService的GetAll方法如何Include关联实体

解决方案

不用完整重写GetAll()方法,ASP.NET Boilerplate 的 AsyncCrudAppService 预留了查询扩展钩子,你只需重写对应的查询构建方法即可注入关联实体的 Include 逻辑,具体操作如下:

1. 为列表查询添加关联实体Include

重写应用服务的CreateFilteredQuery方法,该方法会被内部GetAll流程调用,你可以在这里拼接所有需要的Include逻辑:

using Microsoft.EntityFrameworkCore; // 必须引用,否则Include方法不会生效

public class GettingApprovedAppService : AsyncCrudAppService<GettingApproved, GettingApprovedDto, int, PagedGettingApprovedResultRequestDto, CreateGettingApprovedDto, GettingApprovedDto>
{
    // 构造函数注入Repository,你的原有代码保持不变
    public GettingApprovedAppService(IRepository<GettingApproved, int> repository) : base(repository)
    {
    }

    protected override IQueryable<GettingApproved> CreateFilteredQuery(PagedGettingApprovedResultRequestDto input)
    {
        // 替换下方的导航属性名为你实体实际的关联属性名,多个关联就加多个Include
        return base.CreateFilteredQuery(input)
            .Include(e => e.RelatedEntity1)
            .Include(e => e.RelatedEntity2);
    }
}

你也可以直接从Repository重新构建查询,保留原有过滤逻辑即可。

2. 为单条ID查询添加关联实体Include

如果你调用根据ID获取单条数据的GetAsync接口也需要加载关联实体,额外重写GetEntityByIdAsync方法即可:

protected override Task<GettingApproved> GetEntityByIdAsync(int id)
{
    return Repository.GetAll()
        .Include(e => e.RelatedEntity1)
        .Include(e => e.RelatedEntity2)
        .FirstOrDefaultAsync(e => e.Id == id);
}

注意事项

  • 确保GettingApproved实体中的关联属性为正确定义的导航属性,按需添加virtual关键字适配懒加载规则
  • GettingApprovedDto需要添加对应关联实体的Dto属性,同时配置好AutoMapper映射规则,否则关联数据会在映射到Dto阶段丢失
  • 只有当你需要完全修改默认GetAll的分页、排序、映射逻辑时,才需要完整重写GetAll方法,普通的Include需求用上述方法即可满足

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:06:03