自动映射器构造函数初始化映射问题



我有以下映射配置:-

初始化数据:-

private static IEnumerable<Source> InitializeData()
{
var source= new[]
{
new Source("John", "Doe", "1111111111"),
new Source("Jack", "Handsome", "2222222222"),
new Source("Joe", "Mackenze", "3333333333")
};
return source;
}

源模型:

public class Source
{
private string First { get; set; }
private string Last { get; set; }
private string Phone { get; set; }
public Source(string first, string last, string phone)
{
First = first;
Last = last;
Phone = phone;
}
}

目标模型

public class Destination
{
public string First { get; set; }
public string Last { get; set; }
public string Phone { get; set; }
}

主要

static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
cfg.CreateMap<Source, Destination>().ReverseMap();
});
var mapper = new Mapper(config);
var source= InitializeData();
var people = mapper.Map<IEnumerable<Destination>>(source);
foreach (var p in people)
{
Console.WriteLine("Name: {0}-{1} Phone: {2}", p.First, p.Last, p.Phone);
}
Console.ReadLine();
}

问题描述:

我一直在努力理解源模型和目标模型之间的自动映射器映射。 我的源模型有一个构造函数来初始化或接受来自外部的数据。当我从模型中删除源构造函数时,它工作正常,这意味着平面映射工作正常,但构造函数初始化存在问题。当我在VS2019中调试时,它显示了记录数,但所有字段均为空/空。

上面的映射有什么问题。我已经浏览了自动映射器参考文档,但没有掌握这个问题。

我非常感谢您的帮助!

尝试调用AssertConfigurationIsValid。检查 http://docs.automapper.org/en/latest/Configuration-validation.html。

您的Source属性private。我想你的意思是public.