Automapper Entity Framework Core Include Filter Mapping Issue

automapper c# entity-framework-core

Question

After a bit of research I am aware you cannot have an include filter on an entity framework core clause. My collection entity Skill has a soft delete flag which I need to filter out from the collection sat inside of SkillGroup. I have used a select to create the list I need however the automapper fails as the types are different. I could loop through this and build it in the way automapper want's but I figure there must be a more elegant solution or something I am missing.

public List<SkillGroupModel> GetAllSkillGroupSkills()
    {
        var skillGroups = _context.SkillGroups.Where(x => !x.IsDeleted)
                                            .Select(c => new
                                            {
                                                c,
                                                Skills = c.Skills.Where(i => !i.IsDeleted)
                                            }).AsEnumerable();

        List<SkillGroupModel> rtn = _mapper.Map<List<SkillGroupModel>>(skillGroups);

        //List<SkillGroupModel> rtn = _mapper.Map<List<SkillGroupModel>>(_context.SkillGroups.Include(x => x.Skills.Where(b => !b.IsDeleted).Where(x => !x.IsDeleted));

        return rtn;
    }

Edit -- As per suggested in the comments changed profile to MapFrom:

public class SkillProfile : Profile
{
    public SkillProfile()
    {
        CreateMap<Skill, SkillModel>()
            .ReverseMap();
        CreateMap<SkillGroup, SkillGroupModel>()
            .ForMember(dest => dest.Skills, conf => conf.MapFrom(source => source.Skills.Where(i => !i.IsDeleted)))
            .ReverseMap();
    }
}

And then added ProjectTo to my clause:

public List<SkillGroupModel> GetAllSkillGroupSkills()
{
    var ef = _context.SkillGroups.Where(x => !x.IsDeleted).Include(x => x.Skills).ProjectTo<SkillGroupModel>(_mapper.ConfigurationProvider);
    List <SkillGroupModel> rtn = _mapper.Map<List<SkillGroupModel>>(ef);

    return rtn;
 }
1
0
4/10/2020 1:36:25 PM

Accepted Answer

  1. When you using ProjectTo extension method, don't need to use Include. because query and mapping execute in DataBase.
  2. You can map SkillGroups to List<SkillGroupModel> and don't need to map to SkillGroupModel then List<SkillGroupModel>
public List<SkillGroupModel> GetAllSkillGroupSkills()
{
    return _context.SkillGroups.Where(x => !x.IsDeleted)
                .ProjectTo<List<SkillGroupModel>>(_mapper.ConfigurationProvider).ToList();
}
0
4/10/2020 7:16:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow