AutoMapper自动创建createMap

我有一个叫另一个服务的服务。 这两个服务都使用“相同的类”。 这些类被命名为相同且具有相同的属性但具有不同的命名空间,因此我需要使用AutoMapper将其中一种类型映射到另一种类型。

不,这很简单,因为我所要做的就是CreateMap ,但问题是我们有大约数百个类,我手动需要编写CreateMap ,它的工作连接到我。 是不是有任何Auto CreateMapfunction。 因此,如果我说CreateMap(),那么AutoMapper通过组织工作并找到所有类并自动为这些类和它的子类等执行CreateMap等…

希望有一个简单的解决方案,或者我想一些反思可以解决它…

只需在选项中将CreateMissingTypeMaps设置为true:

 var dto = Mapper.Map (foo, opts => opts.CreateMissingTypeMaps = true); 

如果您需要经常使用它,请将lambda存储在委托字段中:

 static readonly Action _mapperOptions = opts => opts.CreateMissingTypeMaps = true; ... var dto = Mapper.Map(foo, _mapperOptions); 

更新:

上述方法不再适用于最新版本的AutoMapper。

相反,您应该创建一个将CreateMissingTypeMaps设置为true的映射器配置,并从此配置创建一个映射器实例:

 var config = new MapperConfiguration(cfg => { cfg.CreateMissingTypeMaps = true; // other configurations }); var mapper = config.CreateMapper(); 

如果您想继续使用旧的静态API(不再推荐),您也可以这样做:

 Mapper.Initialize(cfg => { cfg.CreateMissingTypeMaps = true; // other configurations }); 

AutoMapper有一个您可以使用的DynamicMap方法:这是一个示例unit testing,用于说明它。

 [TestClass] public class AutoMapper_Example { [TestMethod] public void AutoMapper_DynamicMap() { Source source = new Source {Id = 1, Name = "Mr FooBar"}; Target target = Mapper.DynamicMap(source); Assert.AreEqual(1, target.Id); Assert.AreEqual("Mr FooBar", target.Name); } private class Target { public int Id { get; set; } public string Name { get; set; } } private class Source { public int Id { get; set; } public string Name { get; set; } } } 

您可以在个人资料中设置CreateMissingTypeMaps。 但是,建议为每个映射显式使用CreateMap,并在每个配置文件的unit testing中调用AssertConfigurationIsValid以防止出现无提示错误。

 public class MyProfile : Profile { CreateMissingTypeMaps = true; // Mappings... } 

CreateMissingTypeMaps选项设置为true。 这是ASP.NET Core的AutoMapper.Extensions.Microsoft.DependencyInjection包的示例:

 public class Startup { //... public void ConfigureServices(IServiceCollection services) { //... services.AddAutoMapper(cfg => { cfg.CreateMissingTypeMaps = true; }); //... } //... }