我有一个叫另一个服务的服务.这两个服务都使用"相同的类".这些类被命名为相同且具有相同的属性但具有不同的命名空间,因此我需要使用AutoMapper将其中一种类型映射到另一种类型.
不,这很简单,因为我所要做的就是CreateMap<>
,但问题是我们有大约数百个类,我手动需要编写CreateMap<>
它,并且它的工作连接到我.没有任何自动CreateMap
功能.因此,如果我说CreateMap()然后AutoMapper通过组织工作并找到所有类并自动执行CreateMap
这些类和它的子类等等...
希望有一个简单的解决方案,或者我想一些反思可以解决它...
Tho*_*que 26
CreateMissingTypeMaps
在选项中设置为true:
var dto = Mapper.Map<FooDTO>
(foo, opts => opts.CreateMissingTypeMaps = true);
Run Code Online (Sandbox Code Playgroud)
如果您需要经常使用它,请将lambda存储在委托字段中:
static readonly Action<IMappingOperationOptions> _mapperOptions =
opts => opts.CreateMissingTypeMaps = true;
...
var dto = Mapper.Map<FooDTO>(foo, _mapperOptions);
Run Code Online (Sandbox Code Playgroud)
更新:
上述方法在最新版本的AutoMapper中不再有效.
相反,您应该创建一个CreateMissingTypeMaps
设置为true 的映射器配置,并从此配置创建映射器实例:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMissingTypeMaps = true;
// other configurations
});
var mapper = config.CreateMapper();
Run Code Online (Sandbox Code Playgroud)
如果您想继续使用旧的静态API(不再推荐),您也可以这样做:
Mapper.Initialize(cfg =>
{
cfg.CreateMissingTypeMaps = true;
// other configurations
});
Run Code Online (Sandbox Code Playgroud)
AutoMapper 有一个 DynamicMap 方法,您可以使用它:这是一个示例单元测试来说明它。
[TestClass]
public class AutoMapper_Example
{
[TestMethod]
public void AutoMapper_DynamicMap()
{
Source source = new Source {Id = 1, Name = "Mr FooBar"};
Target target = Mapper.DynamicMap<Target>(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; }
}
}
Run Code Online (Sandbox Code Playgroud)
可以在您的个人资料中设置CreateMissingTypeMaps。但是,建议在每个映射中显式使用CreateMap并在单元测试中为每个配置文件调用AssertConfigurationIsValid,以防止出现静默错误。
public class MyProfile : Profile {
CreateMissingTypeMaps = true;
// Mappings...
}
Run Code Online (Sandbox Code Playgroud)