EF Core中使用include主子表关联导航查询后数据无限循环嵌套问题

问题描述:

下面我有两个实体类Article和Category,Article和Category都有一个彼此的字段,以此可以相互导航查询到对方

在这里插入图片描述
在这里插入图片描述

当我通过Article类用Include导航查询到Category类时,发现Category类又自动导航查询到Article类,就发生了嵌套循环查询,查询代码以及数据如下
return await _context.Articles
                .Include(a => a.Category)
                .ToListAsync();

在这里插入图片描述

解决方案1:

网上找到的解决方案是用select删选,不要查询到Category类里面的Article字段

articles = await _context.Articles
    .Include(a => a.Category)
    .Select(a => new {
    
    
        Id = a.Id,
        Title = a.Title,
        CategoryName = a.Category.Name,
    })
    .ToListAsync();

目前想到最佳解决方案:

我觉得上面的不是最佳的解决方案,因为如果我们要查询的Articles类有很多字段,那岂不是要在select里面写很多代码,所以我想到了另一个解决方案,通过映射Dto的方式,我们先安装所需要的包

AutoMapper.Extensions.Microsoft.DependencyInjection

我们新建一个ArticleDto类,类里面什么都不用写,只需要继承Article类就行
在这里插入图片描述
新建一个映射关系的类

public class MappingProfile : Profile
{
    
    
    public MappingProfile()
    {
    
    
        ///配置Dto映射关系
        CreateMap<Article, ArticleDto>();
        //CreateMap<Category, CategoryDto>();
    }
}

在这里插入图片描述
在Program文件依赖注入映射关系类

builder.Services.AddAutoMapper(typeof(MappingProfile));

在控制器构造函数中使用

  		private readonly BlogDbContext _context;
        private readonly IMapper _mapper;
        public ArticlesController(BlogDbContext context, IMapper mapper)
        {
    
    
            _mapper = mapper;
            _context = context;
        }
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Article>>> GetArticles()
        {
    
    
            var articles = await _context.Articles
                .Include(c=>c.Category)
                .ProjectTo<ArticleDto>(_mapper.ConfigurationProvider)
                .ToListAsync();

            return articles;

        }

在这里插入图片描述
在这里插入图片描述
再次查询结果,已经达到我们想要的效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44442366/article/details/129573007