Skip to content

Instantly share code, notes, and snippets.

@frankhale
Created May 14, 2020 20:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankhale/fe9159b4c7df9bf5d8cfd7656cd816f1 to your computer and use it in GitHub Desktop.
Save frankhale/fe9159b4c7df9bf5d8cfd7656cd816f1 to your computer and use it in GitHub Desktop.
Map single object to list of objects in AutoMapper
using AutoMapper;
using System.Collections.Generic;
namespace AutoMapperSandbox
{
public class SingleObjectToListConverter<T> : ITypeConverter<T, List<T>>
{
public List<T> Convert(T source, List<T> destination, ResolutionContext context)
{
return new List<T>() { source };
}
}
public class Baz
{
public string Qrs { get; set; }
}
public class Foo
{
public string Xyz { get; set; }
public List<Baz> Baz { get; set; }
}
public class FooDto
{
public string Xyz { get; set; }
public Baz Baz { get; set; }
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Baz, List<Baz>>().ConvertUsing<SingleObjectToListConverter<Baz>>();
cfg.CreateMap<Foo, FooDto>().ReverseMap();
});
var mapper = new Mapper(config);
var f = new FooDto()
{
Xyz = "Testing",
Baz = new Baz() { Qrs = "Hello, World!" }
};
var x = mapper.Map<Foo>(f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment