且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自动映射器将单个对象映射到对象列表

更新时间:2022-01-18 22:44:39

我设法在我创建的一个很小的类库中使它正常工作.我注意到的一些位可能会破坏您的代码:

I have managed to get this working in a very small Class Library I created. Bits I noticed that would potentially break your code:

在您要映射的任何地方都没有提及< Contract.Dto.Result,结果>-确保您已经添加了这两个地图

No mention anywhere that you are also mapping < Contract.Dto.Result, Result > - ensure you have added both these maps

var config = new MapperConfiguration(options =>
{
    options.CreateMap<Contract.Dto.Result, List<Result>>(MemberList.Source).ConvertUsing<ResultConverter>();
    options.CreateMap<Contract.Dto.Result, Result>(MemberList.Source);
});

在您的转换器中,我将其更改为使用新的结果列表,而不是目的地

In your converter, I changed this to use a new list of results rather than destination

public List<Result> Convert(Contract.Dto.Result source, List<Result> destination, ResolutionContext context)
{
    var listOfResults = new List<Result>();
    var result = context.Mapper.Map<Contract.Dto.Result, Result>(source);
    listOfResults.Add(result);
    return listOfResults;
}

在实际使用地图时,只需确保您具有正确的语法

When actually using the map, just ensure you have got the correct syntax

var result = new Contract.Dto.Result();
var expected = mapper.Map<List<Result>>(result);

此外,如果使用的是IOC,请确保已注册了连接器.下面的Autofac代码示例

Also, if using IOC, make sure you have registered the conveters. Autofac code example below

 builder.RegisterType<ResultConverter>().AsSelf();
 builder.Register(context => new MapperConfiguration(options=>
 {
     options.CreateMap<Contract.Dto.Result, List<Result>>(MemberList.Source).ConvertUsing<ResultConverter>();
     options.CreateMap<Contract.Dto.Result, Result>(MemberList.Source);
 })).AsSelf().SingleInstance();


 builder.Register(c =>
 {
     //This resolves a new context that can be used later.
     var context = c.Resolve<IComponentContext>();
     var config = context.Resolve<MapperConfiguration>();
     return config.CreateMapper(context.Resolve);
 }).As<IMapper>().InstancePerLifetimeScope();

正如下面评论中提到的OP一样,还要确保使用正确的类型,在这种情况下为List<> vs IList<>

As OP mentioned in comment below, also ensure that the correct types are used, in this instance List<> vs IList<>

在您的项目中尝试所有这些方法,希望能够解决您的问题.如果没有,请告诉我,我可以进一步看看.

Give each of these a try on your project, hopefully that will solve your issues. If not let me know and I can take a further look.