经过一些研究,我知道您不能在实体框架的核心子句上使用包含过滤器。我的集合实体Skill
有一个软删除标志,我需要从SkillGroup
内部的集合中过滤掉该标志。我使用了select创建我需要的列表,但是由于类型不同,自动映射器失败。我可以遍历此过程,并按照automapper想要的方式构建它,但是我认为必须有一个更优雅的解决方案,或者我缺少的东西。
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;
}
编辑-
按照评论中的建议,将个人资料更改为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();
}
}
然后将ProjectTo
添加到我的子句中:
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;
}
答案 0 :(得分:0)
ProjectTo
扩展名方法时,无需使用
Include
。因为查询和映射是在DataBase
中执行的。SkillGroups
映射到List<SkillGroupModel>
,不需要
先映射到SkillGroupModel
,然后映射到List<SkillGroupModel>
public List<SkillGroupModel> GetAllSkillGroupSkills()
{
return _context.SkillGroups.Where(x => !x.IsDeleted)
.ProjectTo<List<SkillGroupModel>>(_mapper.ConfigurationProvider).ToList();
}