aspnetboilerplate执行INNER JOIN查询报AutoMapper映射缺失错误如何解决
错误原因
你遇到的映射报错核心是两点:
- 你LINQ查询
select new { name = s.Name }返回的是匿名类对象集合,而已配置的AutoMapper映射规则只有Student实体到StudentDto、City实体到CityDto的映射,没有匿名类到StudentDto的映射规则,因此AutoMapper无法完成转换。 - 你的代码还存在两处明显语法问题:
StudentDto类定义错误:类名写为Student而非StudentDto,且末尾多了多余的闭合大括号- 构造函数参数赋值逻辑写反,参数名和类字段名冲突,会直接编译报错
解决方案
最推荐的方式是直接在LINQ查询时投影为StudentDto对象,不需要额外配置映射,性能更高也更易维护:
- 先修正
StudentDto的定义:
[AutoMap(typeof(Student))] public class StudentDto : EntityDto { public string Name { get; set; } public int Last_Name { get; set; } public int City_Id { get; set; } // 如果需要关联返回城市名称,可新增对应字段 // public string CityName { get; set; } }
- 修正
StudentAppService的构造函数和查询逻辑:
private readonly IRepository<Student> _studentRepository; private readonly IRepository<City> _cityRepository; // 修正构造函数参数名和赋值逻辑 public StudentAppService(IRepository<Student> studentRepository, IRepository<City> cityRepository) { _studentRepository = studentRepository; _cityRepository = cityRepository; } public List<StudentDto> GetStudentWithCityName() { // 直接投影为StudentDto,不需要二次映射 var data = (from s in _studentRepository.GetAll() join c in _cityRepository.GetAll() on s.City_Id equals c.Id select new StudentDto { Id = s.Id, Name = s.Name, Last_Name = s.Last_Name, City_Id = s.City_Id, // 如果加了CityName字段这里赋值 // CityName = c.Name }).ToList(); return data; }
如果确实需要使用AutoMapper做转换,你需要先定义专门的DTO类接收JOIN后的查询结果,再为该类和StudentDto配置映射规则,相对繁琐,不推荐该场景使用。
内容的提问来源于stack exchange,提问作者mawerick_1
相关产品推荐
相关产品推荐

