AutoMapper自动创建createMap [英] AutoMapper auto create createMap

查看:576
本文介绍了AutoMapper自动创建createMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在调用另一个服务的服务.两种服务都使用相同的类".这些类的名称相同且具有相同的属性,但具有不同的命名空间,因此我需要使用AutoMapper将一种类型映射到另一种类型.

I have a services that is calling another services. Both of the services are using "the same classes". The classes are named same and have the same properties but has different namespace so I need to use AutoMapper to map from one of the type to the other type.

不,这很简单,因为我要做的只是CreateMap<>,但是问题是我们大约需要数百个类来手动编写CreateMap<>,并且可以将其连接到我身上.没有任何自动CreateMap功能.因此,如果我说CreateMap(),则AutoMapper通过Organization工作并找到所有类,并对这些类及其子类等自动执行CreateMap

No it's pretty simple since all I have to do is the CreateMap<>, but the problem is that we have around hundreds of classes that I manually needs to write the CreateMap<> from, and it's works wired to me. Isn't there any Auto CreateMap function. So if I say CreateMap() then AutoMapper workes thru Organisation and finds all classes and automatically does the CreateMap for these Classes and it's subclasses etc etc…

希望有一个简单的解决方案,或者我想可以通过一些反射来解决它...

Hope for a simple solution, or I guess some reflection can fix it...

推荐答案

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

Just set CreateMissingTypeMaps to true in the options:

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

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

If you need to use it often, store the lambda in a delegate field:

static readonly Action<IMappingOperationOptions> _mapperOptions =
    opts => opts.CreateMissingTypeMaps = true;

...

var dto = Mapper.Map<FooDTO>(foo, _mapperOptions);


更新:


UPDATE:

上述方法在AutoMapper的最新版本中不再适用.

The approach described above no longer works in recent versions of AutoMapper.

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

Instead, you should create a mapper configuration with CreateMissingTypeMaps set to true and create a mapper instance from this configuration:

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

如果您想继续使用旧的静态API(不再推荐),也可以执行以下操作:

If you want to keep using the old static API (no longer recommended), you can also do this:

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

这篇关于AutoMapper自动创建createMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆