Automapper 不会从动态对象映射到具有带参数的构造函数的对象

时间:2021-05-21 09:31:24

标签: c# asp.net-core-5.0 automapper-10

我想映射一个从 dapper 查询返回的动态对象列表。查询是:

var allProductsQuery = conn.Query(query, new { mtart = new string[] { "2100" } }).ToList();

目标对象有一个构造函数参数:

    public class ProductModel : MaterialModel
    {
        public IConfiguration _configuration { get; set; }
        public string mould_code { get; set; }
        public string market_class { get; set; }
        public string decoration { get; set; }
        public string photo_url_full
        {
            get
            {
                return string.Concat(_configuration["BaseProductPhotosUrl"], mould_code, "-1.png");
            }
        }

        public ProductModel(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    }

所以我需要映射 List<dynamic> -> List<ProductModel>

我创建了一个 AutoMapper 个人资料:

    public class ProductProfile : Profile
    {
        public ProductProfile()
        {
            CreateMap<dynamic, ProductModel>().ConstructUsingServiceLocator();
        }
    }

我是这样映射的:

List<ProductModel> allProducts = _mapper.Map<List<ProductModel>>(allProductsQuery,
         options => options.ConstructServicesUsing(t => new ProductModel(_configuration)));

这是我找到的唯一避免构建错误的方法(尝试了 official 指南但没有成功)。

问题是结果包含来自源列表的记录数,但peoperties为空。请注意,ProductModel 的构造函数正在工作,因为 photo_url_full 属性已在目标类中正确构建。

0 个答案:

没有答案