根据 cmets,Automapper 团队似乎选择删除 9.0 upgrade 中的 CreateMissingTypeMaps 选项。推测,这是因为自动地图创建可能会导致意外的映射和尴尬的运行时错误,而且,最好在引导时定义所有地图并编译它们,而不是在第一次映射时懒惰地编译它们。
但是,如果您在 Poco 类层之间使用一致的命名方案,则可以很容易地在引导时为两个 poco 层中具有相同名称的所有类复制自动映射功能。例如,如果您的约定是:
namespace Models
{
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
}
namespace Dtos
{
public class MyDto
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
}
然后,您可以在每一层中反映所有符合您命名约定的类,并在匹配的类之间显式创建映射:
const string modelSuffix = "Model";
const string dtoSuffix = "Dto";
var mapperConfiguration = new MapperConfiguration(cfg =>
{
// You may need to repeat this if you have Pocos spread across multiple assemblies
var modelTypes = typeof(MyModel).Assembly
.GetTypes()
.Where(type => type.Namespace == "Models" && type.Name.EndsWith(modelSuffix))
.ToDictionary(t => StripSuffix(t.Name, modelSuffix));
var dtoTypes = typeof(MyDto).Assembly
.GetTypes()
.Where(type => type.Namespace == "Dtos"
&& type.Name.EndsWith(dtoSuffix));
foreach (var dtoType in dtoTypes)
{
if (modelTypes.TryGetValue(StripSuffix(dtoType.Name, dtoSuffix), out var modelType))
{
// I've created forward and reverse mappings ... remove as necessary
cfg.CreateMap(dtoType, modelType);
cfg.CreateMap(modelType, dtoType);
}
}
});
var mapper = mapperConfiguration.CreateMapper();
StripSuffixis simply:
public static string StripSuffix(string someString, string someSuffix)
{
if (someString.EndsWith(someSuffix))
return someString.Substring(0, someString.Length - someSuffix.Length);
else
return someString;
}
您现在可以根据需要进行测试:
var model = new MyModel
{
Id = 1,
Name = "Foo",
Amount = 1.23m,
Date = DateTime.UtcNow
};
var dto = mapper.Map<MyDto>(model);
var backTomodel = mapper.Map<MyModel>(dto);