using AutoMapper;
using System.Collections.Generic;
public class CollectionMappingProfile : Profile
{
public CollectionMappingProfile()
{
CreateMap, ICollection>()
.ConstructUsing((src, context) => context.Mapper.Map>(src));
CreateMap();
}
}
然后,在你的项目启动时,注册这个自定义映射配置类:
using AutoMapper;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 注册AutoMapper
services.AddAutoMapper(typeof(Startup));
// 注册自定义映射配置
Mapper.Initialize(cfg =>
{
cfg.AddProfile();
});
}
}
现在,当你使用AutoMapper映射ICollection属性时,它应该工作正常了:
public class Source
{
public ICollection Numbers { get; set; }
}
public class Destination
{
public ICollection Numbers { get; set; }
}
public class Example
{
public void MapExample()
{
var source = new Source { Numbers = new List { 1, 2, 3 } };
var destination = Mapper.Map(source);
Console.WriteLine(string.Join(",", destination.Numbers)); // 输出 "1,2,3"
}
}