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

aspnetboilerplate执行INNER JOIN查询报AutoMapper映射缺失错误如何解决

错误原因

你遇到的映射报错核心是两点:

  1. 你LINQ查询select new { name = s.Name }返回的是匿名类对象集合,而已配置的AutoMapper映射规则只有Student实体到StudentDto、City实体到CityDto的映射,没有匿名类到StudentDto的映射规则,因此AutoMapper无法完成转换。
  2. 你的代码还存在两处明显语法问题:
    • StudentDto类定义错误:类名写为Student而非StudentDto,且末尾多了多余的闭合大括号
    • 构造函数参数赋值逻辑写反,参数名和类字段名冲突,会直接编译报错

解决方案

最推荐的方式是直接在LINQ查询时投影为StudentDto对象,不需要额外配置映射,性能更高也更易维护:

  1. 先修正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; }
}
  1. 修正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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:51:02